Best Kotest code snippet using io.kotest.property.internal.Counter
NotificationStoreRealTimeTests.kt
Source:NotificationStoreRealTimeTests.kt  
...133      Result.success(storePage)134    )135    // WHEN136    store.fetch().getOrThrow()137    val initialCounter = InitialNotificationStoreCounts(store)138    val chosenIndex = anyIndexForDefaultEdgeArraySize139    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))140    // THEN141    coVerify(exactly = 1) { fetchStorePageInteractor.invoke(any(), any(), any()) }142    store.size.shouldBeExactly(defaultEdgeArraySize)143    store.totalCount.shouldBeExactly(initialCounter.totalCount)144    store.unreadCount.shouldBeExactly(initialCounter.unreadCount)145    Unit146  }147  @Test148  fun test_notifyReadNotification_withDefaultStorePredicateAndUnreadAndExists_shouldUpdateNotification() = runBlocking {149    // GIVEN150    val predicate = StorePredicate()151    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unread)152    val store = createStoreDirector(153      predicate,154      Result.success(storePage)155    )156    // WHEN157    store.fetch().getOrThrow()158    val initialCounter = InitialNotificationStoreCounts(store)159    val chosenIndex = anyIndexForDefaultEdgeArraySize160    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))161    // THEN162    store[chosenIndex].readAt.shouldNotBeNull()163    coVerify(exactly = 1) { fetchStorePageInteractor.invoke(any(), any(), any()) }164    store.size.shouldBeExactly(defaultEdgeArraySize)165    store.totalCount.shouldBeExactly(initialCounter.totalCount)166    store.unreadCount.shouldBeExactly(initialCounter.unreadCount - 1)167    Unit168  }169  @Test170  fun test_notifyReadNotification_withDefaultStorePredicateAndUnseenAndExists_shouldUpdateNotification() = runBlocking {171    // GIVEN172    val predicate = StorePredicate()173    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unseen)174    val store = createStoreDirector(175      predicate,176      Result.success(storePage)177    )178    // WHEN179    store.fetch().getOrThrow()180    val initialCounter = InitialNotificationStoreCounts(store)181    val chosenIndex = anyIndexForDefaultEdgeArraySize182    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))183    // THEN184    store[chosenIndex].readAt.shouldNotBeNull()185    store[chosenIndex].seenAt.shouldNotBeNull()186    coVerify(exactly = 1) { fetchStorePageInteractor.invoke(any(), any(), any()) }187    store.size.shouldBeExactly(defaultEdgeArraySize)188    store.totalCount.shouldBeExactly(initialCounter.totalCount)189    store.unreadCount.shouldBeExactly(initialCounter.unreadCount - 1)190    store.unseenCount.shouldBeExactly(initialCounter.unseenCount - 1)191    Unit192  }193  @Test194  fun test_notifyReadNotification_withDefaultStorePredicateAndDoesntExists_shouldRefresh() = runBlocking {195    // GIVEN196    val predicate = StorePredicate()197    val storePage = givenPageStore(predicate, defaultEdgeArraySize)198    val store = createStoreDirector(199      predicate,200      Result.success(storePage)201    )202    // WHEN203    store.fetch().getOrThrow()204    val initialCounter = InitialNotificationStoreCounts(store)205    storeRealTime.processMessage(RealTimeEventMock.ReadNotification("Not exists"))206    // THEN207    coVerify(exactly = 2) { fetchStorePageInteractor.invoke(any(), any(), any()) }208    store.size.shouldBeExactly(defaultEdgeArraySize)209    store.totalCount.shouldBeExactly(initialCounter.totalCount)210    storePage.edges.mapIndexed { index, edge ->211      store[index].id.shouldBe(edge.node.id)212    }213    Unit214  }215  @Test216  fun test_notifyUnreadNotification_withDefaultStorePredicateAndReadAndExists_shouldUpdateNotification() = runBlocking {217    // GIVEN218    val predicate = StorePredicate()219    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Read)220    val store = createStoreDirector(221      predicate,222      Result.success(storePage)223    )224    // WHEN225    store.fetch().getOrThrow()226    val initialCounter = InitialNotificationStoreCounts(store)227    val chosenIndex = anyIndexForDefaultEdgeArraySize228    storeRealTime.processMessage(RealTimeEventMock.UnreadNotification(chosenIndex.toString()))229    // THEN230    store[chosenIndex].readAt.shouldBeNull()231    coVerify(exactly = 1) { fetchStorePageInteractor.invoke(any(), any(), any()) }232    store.size.shouldBeExactly(defaultEdgeArraySize)233    store.totalCount.shouldBeExactly(initialCounter.totalCount)234    store.unreadCount.shouldBeExactly(initialCounter.unreadCount + 1)235    store.unseenCount.shouldBeExactly(initialCounter.unseenCount)236    Unit237  }238  @Test239  fun test_notifyUnreadNotification_withDefaultStorePredicateAndUnreadAndExists_shouldUpdateNotification() = runBlocking {240    // GIVEN241    val predicate = StorePredicate()242    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unread)243    val store = createStoreDirector(244      predicate,245      Result.success(storePage)246    )247    // WHEN248    store.fetch().getOrThrow()249    val initialCounter = InitialNotificationStoreCounts(store)250    val chosenIndex = anyIndexForDefaultEdgeArraySize251    storeRealTime.processMessage(RealTimeEventMock.UnreadNotification(chosenIndex.toString()))252    // THEN253    store[chosenIndex].readAt.shouldBeNull()254    coVerify(exactly = 1) { fetchStorePageInteractor.invoke(any(), any(), any()) }255    store.size.shouldBeExactly(defaultEdgeArraySize)256    store.totalCount.shouldBeExactly(initialCounter.totalCount)257    store.unreadCount.shouldBeExactly(initialCounter.unreadCount)258    store.unseenCount.shouldBeExactly(initialCounter.unseenCount)259    Unit260  }261  @Test262  fun test_notifyUnreadNotification_withDefaultStorePredicateAndNotExists_shouldRefresh() = runBlocking {263    // GIVEN264    val predicate = StorePredicate()265    val storePage = givenPageStore(predicate, defaultEdgeArraySize)266    val store = createStoreDirector(267      predicate,268      Result.success(storePage)269    )270    // WHEN271    store.fetch().getOrThrow()272    storeRealTime.processMessage(RealTimeEventMock.UnreadNotification("Not exists"))273    // THEN274    coVerify(exactly = 2) { fetchStorePageInteractor.invoke(any(), any(), any()) }275    store.size.shouldBeExactly(defaultEdgeArraySize)276    Unit277  }278  @Test279  fun test_notifyDeleteNotification_withDefaultStorePredicateAndUnreadAndExists_shouldRemoveNotificationAndUnreadCount() = runBlocking {280    // GIVEN281    val predicate = StorePredicate()282    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unread)283    val store = createStoreDirector(284      predicate,285      Result.success(storePage)286    )287    // WHEN288    store.fetch().getOrThrow()289    val initialCounter = InitialNotificationStoreCounts(store)290    val chosenIndex = anyIndexForDefaultEdgeArraySize291    val removedNotificationId = store[chosenIndex].id292    storeRealTime.processMessage(RealTimeEventMock.DeleteNotification(chosenIndex.toString()))293    // THEN294    coVerify(exactly = 1) { fetchStorePageInteractor.invoke(any(), any(), any()) }295    store.totalCount.shouldBeExactly(initialCounter.totalCount - 1)296    store.unreadCount.shouldBeExactly(initialCounter.unreadCount - 1)297    store.forEach { notification ->298      notification.id.shouldNotBe(removedNotificationId)299    }300  }301  @Test302  fun test_notifyDeleteNotification_withDefaultStorePredicateAndUnseenAndExists_shouldUpdateUnseenCount() = runBlocking {303    // GIVEN304    val predicate = StorePredicate()305    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unseen)306    val store = createStoreDirector(307      predicate,308      Result.success(storePage)309    )310    // WHEN311    store.fetch().getOrThrow()312    val initialCounter = InitialNotificationStoreCounts(store)313    val chosenIndex = anyIndexForDefaultEdgeArraySize314    storeRealTime.processMessage(RealTimeEventMock.DeleteNotification(chosenIndex.toString()))315    // THEN316    coVerify(exactly = 1) { fetchStorePageInteractor.invoke(any(), any(), any()) }317    store.unseenCount.shouldBeExactly(initialCounter.unseenCount - 1)318    Unit319  }320  @Test321  fun test_notifyDeleteNotification_withDefaultStorePredicateAndSeenAndExists_shouldSameUnseenCount() = runBlocking {322    // GIVEN323    val predicate = StorePredicate()324    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Seen)325    val store = createStoreDirector(326      predicate,327      Result.success(storePage)328    )329    // WHEN330    store.fetch().getOrThrow()331    val initialCounter = InitialNotificationStoreCounts(store)332    val chosenIndex = anyIndexForDefaultEdgeArraySize333    storeRealTime.processMessage(RealTimeEventMock.DeleteNotification(chosenIndex.toString()))334    // THEN335    coVerify(exactly = 1) { fetchStorePageInteractor.invoke(any(), any(), any()) }336    store.unseenCount.shouldBeExactly(initialCounter.unseenCount)337    Unit338  }339  @Test340  fun test_notifyDeleteNotification_withDefaultStorePredicateAndNotExists_shouldDoNothing() = runBlocking {341    // GIVEN342    val predicate = StorePredicate()343    val storePage = givenPageStore(predicate, defaultEdgeArraySize)344    val store = createStoreDirector(345      predicate,346      Result.success(storePage)347    )348    // WHEN349    store.fetch().getOrThrow()350    val initialCounter = InitialNotificationStoreCounts(store)351    storeRealTime.processMessage(RealTimeEventMock.DeleteNotification("Not exists"))352    // THEN353    coVerify(exactly = 1) { fetchStorePageInteractor.invoke(any(), any(), any()) }354    store.totalCount.shouldBeExactly(initialCounter.totalCount)355    store.unreadCount.shouldBeExactly(initialCounter.unreadCount)356    store.unseenCount.shouldBeExactly(initialCounter.unseenCount)357    Unit358  }359  @Test360  fun test_notifyReadAllNotification_withDefaultStorePredicate_shouldRefresh() = runBlocking {361    // GIVEN362    val predicate = StorePredicate()363    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Read)364    val store = createStoreDirector(365      predicate,366      Result.success(storePage)367    )368    // WHEN369    store.fetch().getOrThrow()370    storeRealTime.processMessage(RealTimeEventMock.ReadAllNotification)371    // THEN372    coVerify(exactly = 2) { fetchStorePageInteractor.invoke(any(), any(), any()) }373    store.size.shouldBeExactly(defaultEdgeArraySize)374    store.forEach { notification ->375      notification.readAt.shouldNotBeNull()376    }377  }378  @Test379  fun test_notifySeenAllNotification_withDefaultStorePredicate_shouldRefresh() = runBlocking {380    // GIVEN381    val predicate = StorePredicate()382    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Read)383    val store = createStoreDirector(384      predicate,385      Result.success(storePage)386    )387    // WHEN388    store.fetch().getOrThrow()389    storeRealTime.processMessage(RealTimeEventMock.SeenAllNotification)390    // THEN391    coVerify(exactly = 2) { fetchStorePageInteractor.invoke(any(), any(), any()) }392    store.size.shouldBeExactly(defaultEdgeArraySize)393    store.forEach { notification ->394      notification.seenAt.shouldNotBeNull()395    }396  }397  // MARK: - Observer tests398  @Test399  fun test_addContentObserver_ShouldNotifyRefreshStore() = runBlocking {400    // GIVEN401    val contentObserver = ContentObserverMock()402    val predicate = StorePredicate()403    val storePage = givenPageStore(predicate, defaultEdgeArraySize)404    val store = createStoreDirector(405      predicate,406      Result.success(storePage)407    )408    store.addContentObserver(contentObserver)409    // WHEN410    storeRealTime.processMessage(RealTimeEventMock.NewNotification("NewNotification"))411    // THEN412    delay(100)413    contentObserver.reloadStoreCounter.shouldBeExactly(1)414    contentObserver.reloadStoreSpy.shouldNotBeEmpty()415    Unit416  }417  @Test418  fun test_notifyReadNotification_withReadStorePredicateAndExists_ShouldDidChangeDelegate() = runBlocking {419    // GIVEN420    val contentObserver = ContentObserverMock()421    val predicate = StorePredicate(read = true)422    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Read)423    val store = createStoreDirector(424      predicate,425      Result.success(storePage)426    )427    store.addContentObserver(contentObserver)428    // WHEN429    store.fetch().getOrThrow()430    val chosenIndex = anyIndexForDefaultEdgeArraySize431    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))432    // THEN433    contentObserver.reloadStoreCounter.shouldBeExactly(0)434    contentObserver.didChangeCounter.shouldBeExactly(1)435    contentObserver.didChangeSpy[0].indexes.shouldBe(listOf(chosenIndex))436  }437  @Test438  fun test_notifyReadNotification_withReadStorePredicateAndDoesntExist_ShouldNotifyReadNotification() = runBlocking {439    // GIVEN440    val contentObserver = ContentObserverMock()441    val predicate = StorePredicate(read = true)442    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Read)443    val store = createStoreDirector(444      predicate,445      Result.success(storePage)446    )447    store.addContentObserver(contentObserver)448    // WHEN449    store.fetch().getOrThrow()450    storeRealTime.processMessage(RealTimeEventMock.ReadNotification("Not exists"))451    // THEN452    delay(100)453    contentObserver.reloadStoreCounter.shouldBeExactly(1)454    contentObserver.didChangeCounter.shouldBeExactly(0)455    Unit456  }457  @Test458  fun test_notifyReadNotification_WithUnreadStorePredicateAndExists_ShouldNotifyChange() = runBlocking {459    // GIVEN460    val contentObserver = ContentObserverMock()461    val predicate = StorePredicate(read = false)462    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unread)463    val store = createStoreDirector(464      predicate,465      Result.success(storePage)466    )467    store.addContentObserver(contentObserver)468    // WHEN469    store.fetch().getOrThrow()470    val chosenIndex = anyIndexForDefaultEdgeArraySize471    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))472    // THEN473    contentObserver.reloadStoreCounter.shouldBeExactly(0)474    contentObserver.didChangeCounter.shouldBeExactly(0)475    contentObserver.didDeleteCounter.shouldBeExactly(1)476    contentObserver.didDeleteSpy[0].indexes.shouldBe(listOf(chosenIndex))477  }478  @Test479  fun test_notifyDeleteNotification_WithDefaultStorePredicateAndExists_ShouldNotifyDeletion() = runBlocking {480    // GIVEN481    val contentObserver = ContentObserverMock()482    val predicate = StorePredicate()483    val storePage = givenPageStore(predicate, defaultEdgeArraySize)484    val store = createStoreDirector(485      predicate,486      Result.success(storePage)487    )488    store.addContentObserver(contentObserver)489    // WHEN490    store.fetch().getOrThrow()491    val chosenIndex = anyIndexForDefaultEdgeArraySize492    storeRealTime.processMessage(RealTimeEventMock.DeleteNotification(chosenIndex.toString()))493    // THEN494    contentObserver.reloadStoreCounter.shouldBeExactly(0)495    contentObserver.didChangeCounter.shouldBeExactly(0)496    contentObserver.didDeleteCounter.shouldBeExactly(1)497    contentObserver.didDeleteSpy[0].indexes.shouldBe(listOf(chosenIndex))498  }499  @Test500  fun test_notifyMarkAllRead_WithUnreadStorePredicate_ShouldClearStore() = runBlocking {501    // GIVEN502    val contentObserver = ContentObserverMock()503    val predicate = StorePredicate(read = false)504    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unread)505    val store = createStoreDirector(506      predicate,507      Result.success(storePage)508    )509    store.addContentObserver(contentObserver)510    // WHEN511    store.fetch().getOrThrow()512    val initialCounts = InitialNotificationStoreCounts(store)513    storeRealTime.processMessage(RealTimeEventMock.ReadAllNotification)514    // THEN515    contentObserver.reloadStoreCounter.shouldBeExactly(0)516    contentObserver.didChangeCounter.shouldBeExactly(0)517    contentObserver.didDeleteCounter.shouldBeExactly(1)518    contentObserver.didDeleteSpy[0].indexes.shouldBe(0.until(initialCounts.totalCount).toList())519    store.totalCount.shouldBeExactly(0)520    store.unreadCount.shouldBeExactly(0)521    store.unseenCount.shouldBeExactly(0)522    Unit523  }524  @Test525  fun test_notifyMarkAllSeen_WithUnseenStorePredicate_ShouldClearStore() = runBlocking {526    // GIVEN527    val contentObserver = ContentObserverMock()528    val predicate = StorePredicate(seen = false)529    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unseen)530    val store = createStoreDirector(531      predicate,532      Result.success(storePage)533    )534    store.addContentObserver(contentObserver)535    // WHEN536    store.fetch().getOrThrow()537    val initialCounts = InitialNotificationStoreCounts(store)538    storeRealTime.processMessage(RealTimeEventMock.SeenAllNotification)539    // THEN540    contentObserver.reloadStoreCounter.shouldBeExactly(0)541    contentObserver.didChangeCounter.shouldBeExactly(0)542    contentObserver.didDeleteCounter.shouldBeExactly(1)543    contentObserver.didDeleteSpy[0].indexes.shouldBe(0.until(initialCounts.totalCount).toList())544    store.totalCount.shouldBeExactly(0)545    store.unreadCount.shouldBeExactly(0)546    store.unseenCount.shouldBeExactly(0)547    Unit548  }549  @Test550  fun test_notifyNewNotification_WithDefaultStorePredicate_ShouldRefreshStoreAndCounters() = runBlocking {551    // GIVEN552    val countObserver = CountObserverMock()553    val predicate = StorePredicate()554    val storePage = givenPageStore(predicate, defaultEdgeArraySize)555    val store = createStoreDirector(556      predicate,557      Result.success(storePage)558    )559    store.addCountObserver(countObserver)560    // WHEN561    store.fetch().getOrThrow()562    storeRealTime.processMessage(RealTimeEventMock.NewNotification("NewId"))563    // THEN564    delay(100)565    countObserver.totalCountCounter.shouldBeExactly(2)566    countObserver.unreadCountCounter.shouldBeExactly(2)567    countObserver.unseenCountCounter.shouldBeExactly(2)568    Unit569  }570  @Test571  fun test_notifyReadNotification_WithDefaultStorePredicateAndUnread_ShouldRefreshStoreAndCounters() = runBlocking {572    // GIVEN573    val countObserver = CountObserverMock()574    val predicate = StorePredicate()575    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unread)576    val store = createStoreDirector(577      predicate,578      Result.success(storePage)579    )580    store.addCountObserver(countObserver)581    // WHEN582    store.fetch().getOrThrow()583    val initialCounts = InitialNotificationStoreCounts(store)584    val chosenIndex = anyIndexForDefaultEdgeArraySize585    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))586    // THEN587    countObserver.totalCountCounter.shouldBeExactly(1)588    countObserver.totalCountSpy[0].count.shouldBeExactly(store.totalCount)589    countObserver.unreadCountCounter.shouldBeExactly(2)590    countObserver.unreadCountSpy[0].count.shouldBeExactly(initialCounts.unreadCount)591    countObserver.unreadCountSpy[1].count.shouldBeExactly(initialCounts.unreadCount - 1)592    Unit593  }594  @Test595  fun test_notifyReadNotification_WithDefaultStorePredicateAndRead_ShouldRefreshStoreAndCounters() = runBlocking {596    // GIVEN597    val countObserver = CountObserverMock()598    val predicate = StorePredicate()599    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Read)600    val store = createStoreDirector(601      predicate,602      Result.success(storePage)603    )604    store.addCountObserver(countObserver)605    // WHEN606    store.fetch().getOrThrow()607    val chosenIndex = anyIndexForDefaultEdgeArraySize608    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))609    // THEN610    delay(100)611    countObserver.totalCountCounter.shouldBeExactly(1)612    countObserver.totalCountSpy[0].count.shouldBeExactly(store.size)613    countObserver.unreadCountCounter.shouldBeExactly(0)614    Unit615  }616  @Test617  fun test_notifyReadNotification_WithDefaultStorePredicateAndUnseen_ShouldRefreshStoreAndCounters() = runBlocking {618    // GIVEN619    val countObserver = CountObserverMock()620    val predicate = StorePredicate()621    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unseen)622    val store = createStoreDirector(623      predicate,624      Result.success(storePage)625    )626    store.addCountObserver(countObserver)627    // WHEN628    store.fetch().getOrThrow()629    val initialCounts = InitialNotificationStoreCounts(store)630    val chosenIndex = anyIndexForDefaultEdgeArraySize631    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))632    // THEN633    countObserver.totalCountCounter.shouldBeExactly(1)634    countObserver.totalCountSpy[0].count.shouldBeExactly(store.size)635    countObserver.unseenCountCounter.shouldBeExactly(2)636    countObserver.unseenCountSpy[0].count.shouldBeExactly(initialCounts.unseenCount)637    countObserver.unseenCountSpy[1].count.shouldBeExactly(initialCounts.unseenCount - 1)638    Unit639  }640  @Test641  fun test_notifyReadNotification_WithDefaultStorePredicateAndSeen_ShouldRefreshStoreAndCounters() = runBlocking {642    // GIVEN643    val countObserver = CountObserverMock()644    val predicate = StorePredicate()645    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Seen)646    val store = createStoreDirector(647      predicate,648      Result.success(storePage)649    )650    store.addCountObserver(countObserver)651    // WHEN652    store.fetch().getOrThrow()653    val chosenIndex = anyIndexForDefaultEdgeArraySize654    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))655    // THEN656    countObserver.totalCountCounter.shouldBeExactly(1)657    countObserver.totalCountSpy[0].count.shouldBeExactly(store.size)658    countObserver.unseenCountCounter.shouldBeExactly(0)659    Unit660  }661  @Test662  fun test_notifyReadNotification_WithUnreadStorePredicateAndUnread_ShouldRefreshStoreAndCounters() = runBlocking {663    // GIVEN664    val countObserver = CountObserverMock()665    val predicate = StorePredicate(read = false)666    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unread)667    val store = createStoreDirector(668      predicate,669      Result.success(storePage)670    )671    store.addCountObserver(countObserver)672    // WHEN673    store.fetch().getOrThrow()674    val initialCounts = InitialNotificationStoreCounts(store)675    val chosenIndex = anyIndexForDefaultEdgeArraySize676    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))677    // THEN678    delay(100)679    countObserver.totalCountCounter.shouldBeExactly(2)680    countObserver.unreadCountCounter.shouldBeExactly(2)681    countObserver.unreadCountSpy[0].count.shouldBeExactly(initialCounts.unreadCount)682    countObserver.unreadCountSpy[1].count.shouldBeExactly(initialCounts.unreadCount - 1)683    Unit684  }685  @Test686  fun test_notifyReadNotification_WithUnreadStorePredicateAndRead_ShouldRefreshStoreAndCounters() = runBlocking {687    // GIVEN688    val countObserver = CountObserverMock()689    val predicate = StorePredicate(read = false)690    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Read)691    val store = createStoreDirector(692      predicate,693      Result.success(storePage)694    )695    store.addCountObserver(countObserver)696    // WHEN697    store.fetch().getOrThrow()698    val chosenIndex = anyIndexForDefaultEdgeArraySize699    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))700    countObserver.totalCountCounter.shouldBeExactly(1)701    countObserver.unreadCountCounter.shouldBeExactly(0)702    Unit703  }704  @Test705  fun test_notifyReadNotification_WithUnreadStorePredicateAndUnseen_ShouldRefreshStoreAndCounters() = runBlocking {706    // GIVEN707    val countObserver = CountObserverMock()708    val predicate = StorePredicate(read = false)709    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unseen)710    val store = createStoreDirector(711      predicate,712      Result.success(storePage)713    )714    store.addCountObserver(countObserver)715    // WHEN716    store.fetch().getOrThrow()717    val initialCounts = InitialNotificationStoreCounts(store)718    val chosenIndex = anyIndexForDefaultEdgeArraySize719    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))720    // THEN721    countObserver.totalCountCounter.shouldBeExactly(2)722    countObserver.totalCountSpy[0].count.shouldBeExactly(initialCounts.totalCount)723    countObserver.totalCountSpy[1].count.shouldBeExactly(initialCounts.totalCount - 1)724    countObserver.unseenCountCounter.shouldBeExactly(2)725    countObserver.unseenCountSpy[0].count.shouldBeExactly(initialCounts.unseenCount)726    countObserver.unseenCountSpy[1].count.shouldBeExactly(initialCounts.unseenCount - 1)727    Unit728  }729  @Test730  fun test_notifyReadNotification_WithUnreadStorePredicateAndSeen_ShouldRefreshStoreAndCounters() = runBlocking {731    // GIVEN732    val countObserver = CountObserverMock()733    val predicate = StorePredicate(read = false)734    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Seen)735    val store = createStoreDirector(736      predicate,737      Result.success(storePage)738    )739    store.addCountObserver(countObserver)740    // WHEN741    store.fetch().getOrThrow()742    val initialCounts = InitialNotificationStoreCounts(store)743    val chosenIndex = anyIndexForDefaultEdgeArraySize744    storeRealTime.processMessage(RealTimeEventMock.ReadNotification(chosenIndex.toString()))745    // THEN746    countObserver.totalCountCounter.shouldBeExactly(2)747    countObserver.totalCountSpy[0].count.shouldBeExactly(initialCounts.totalCount)748    countObserver.totalCountSpy[1].count.shouldBeExactly(initialCounts.totalCount - 1)749    countObserver.unseenCountCounter.shouldBeExactly(0)750    Unit751  }752  @Test753  fun test_notifyReadAllNotification_WithDefaultStorePredicateAndRead_ShouldNotifyCounters() = runBlocking {754    // GIVEN755    val countObserver = CountObserverMock()756    val predicate = StorePredicate()757    val storePage = givenPageStore(predicate, defaultEdgeArraySize)758    val store = createStoreDirector(759      predicate,760      Result.success(storePage)761    )762    store.addCountObserver(countObserver)763    // WHEN764    store.fetch().getOrThrow()765    val initialCounts = InitialNotificationStoreCounts(store)766    coEvery { fetchStorePageInteractor.invoke(any(), any(), any()) } returns givenPageStore(predicate, 15, forceProperty = ForceProperty.Read)767    storeRealTime.processMessage(RealTimeEventMock.ReadAllNotification)768    // THEN769    delay(100)770    countObserver.totalCountCounter.shouldBeExactly(2)771    countObserver.unreadCountCounter.shouldBeExactly(1)772    countObserver.unreadCountSpy[0].count.shouldBeExactly(initialCounts.unreadCount)773    countObserver.unseenCountCounter.shouldBeExactly(1)774    Unit775  }776  @Test777  fun test_notifySeenAllNotification_WithDefaultStorePredicate_ShouldNotifyCounters() = runBlocking {778    // GIVEN779    val countObserver = CountObserverMock()780    val predicate = StorePredicate()781    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unread)782    val store = createStoreDirector(783      predicate,784      Result.success(storePage)785    )786    store.addCountObserver(countObserver)787    // WHEN788    store.fetch().getOrThrow()789    val initialCounts = InitialNotificationStoreCounts(store)790    coEvery { fetchStorePageInteractor.invoke(any(), any(), any()) } returns givenPageStore(predicate, 15, forceProperty = ForceProperty.Read)791    storeRealTime.processMessage(RealTimeEventMock.SeenAllNotification)792    // THEN793    delay(100)794    countObserver.totalCountCounter.shouldBeExactly(2)795    countObserver.unreadCountCounter.shouldBeExactly(1)796    countObserver.unreadCountSpy[0].count.shouldBeExactly(initialCounts.unreadCount)797    countObserver.unseenCountCounter.shouldBeExactly(1)798    countObserver.unseenCountSpy[0].count.shouldBeExactly(initialCounts.unseenCount)799    Unit800  }801  @Test802  fun test_removeCountObserver() = runBlocking {803    // GIVEN804    val countObserver = CountObserverMock()805    val predicate = StorePredicate()806    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unread)807    val store = createStoreDirector(808      predicate,809      Result.success(storePage)810    )811    // WHEN812    store.addCountObserver(countObserver)813    store.removeCountObserver(countObserver)814    storeRealTime.processMessage(RealTimeEventMock.SeenAllNotification)815    store.fetch().getOrThrow()816    // THEN817    countObserver.totalCountCounter.shouldBeExactly(0)818    Unit819  }820  @Test821  fun test_removeContentObserver() = runBlocking {822    // GIVEN823    val contentObserver = ContentObserverMock()824    val predicate = StorePredicate()825    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unread)826    val store = createStoreDirector(827      predicate,828      Result.success(storePage)829    )830    // WHEN831    store.addContentObserver(contentObserver)832    store.removeContentObserver(contentObserver)833    storeRealTime.processMessage(RealTimeEventMock.SeenAllNotification)834    store.fetch().getOrThrow()835    // THEN836    contentObserver.didInsertCounter.shouldBeExactly(0)837    Unit838  }839  @Test840  fun test_notifyArchiveNotification_withDefaultStorePredicateAndExists_shouldDoNothing() = runBlocking {841    // GIVEN842    val predicate = StorePredicate()843    val storePage = givenPageStore(predicate, defaultEdgeArraySize, forceProperty = ForceProperty.Unarchived)844    val store = createStoreDirector(845      predicate,846      Result.success(storePage)847    )848    // WHEN849    store.fetch().getOrThrow()850    val initialCounter = InitialNotificationStoreCounts(store)851    val chosenIndex = anyIndexForDefaultEdgeArraySize852    storeRealTime.processMessage(853      RealTimeEventMock.ArchiveNotification(chosenIndex.toString())854    )855    // THEN856    coVerify(exactly = 1) { fetchStorePageInteractor.invoke(any(), any(), any()) }857    store.size.shouldBeExactly(defaultEdgeArraySize - 1)858    store.totalCount.shouldBeExactly(initialCounter.totalCount - 1)859    Unit860  }861}...PersistentExpiringLockManagerTest.kt
Source:PersistentExpiringLockManagerTest.kt  
...68            val lockId = createLockIdentity()69            manager.tryAcquire(lockId) { }.shouldBeTrue()70            lockIds.add(lockId)71        }72        val doneThreadCounter = AtomicInteger(0)73        val releaseExceptions = ConcurrentHashMap.newKeySet<Exception>()74        val executor = Executors.newFixedThreadPool(8)75        for (i in 0 until 50) {76            val lockId = lockIds[i]77            executor.execute {78                try {79                    TimeUnit.MILLISECONDS.sleep((10 + i).toLong())80                    manager.release(lockId)81                } catch (e: Exception) {82                    releaseExceptions.add(e)83                } finally {84                    doneThreadCounter.incrementAndGet()85                }86            }87        }88        while (doneThreadCounter.get() != 50) {89            TimeUnit.MILLISECONDS.sleep(100) // wait for releasing all locks90        }91        val releaseLockStates = mutableListOf<PersistentExpiringDistributedLock.State>()92        for (i in 0 until 50) {93            val lockId = lockIds[i]94            val stateOptional = manager.getLockState(lockId)95            if (stateOptional.isPresent) {96                logger.error("exist state for release lock $lockId state = ${stateOptional.get()}")97                releaseLockStates.add(stateOptional.get())98            }99        }100        releaseExceptions.shouldBeEmpty()101        releaseLockStates.shouldBeEmpty()102    }...benchmark.kt
Source:benchmark.kt  
1package prettyprinter2import io.kotest.property.Arb3import io.kotest.property.RandomSource4import io.kotest.property.arbitrary.alphanumeric5import io.kotest.property.arbitrary.bind6import io.kotest.property.arbitrary.flatMap7import io.kotest.property.arbitrary.int8import io.kotest.property.arbitrary.list9import io.kotest.property.arbitrary.map10import io.kotest.property.arbitrary.next11import io.kotest.property.arbitrary.string12import prettyprinter.symbols.lparen13import prettyprinter.symbols.rparen14import kotlin.math.max15import kotlin.math.min16import kotlin.test.BeforeTest17import kotlin.test.Test18import kotlin.time.Duration19import kotlin.time.ExperimentalTime20import kotlin.time.measureTime21data class Program(val binds: Binds)22data class Binds(val map: Map<String, LambdaForm>)23data class LambdaForm(val free: List<String>, val bound: List<String>, val body: Expr)24sealed class Expr {25    data class Let(val binds: Binds, val body: Expr): Expr()26    data class Case(val scrutinee: Expr, val alts: List<Alt>): Expr()27    data class AppF(val f: String, val args: List<String>): Expr()28    data class AppC(val c: String, val args: List<String>): Expr()29    data class AppP(val op: String, val x: String, val y: String): Expr()30    data class LitE(val lit: Int): Expr()31}32data class Alt(val con: String, val args: List<String>, val body: Expr)33/* Set up value generators. */34val keywordArb: Arb<String> = Arb.string(5..7, Arb.alphanumeric())35val keywordUcArb: Arb<String> = keywordArb.map { it.replaceFirstChar { c -> c.uppercaseChar() } }36val keywordsArb: Arb<List<String>> = Arb.list(keywordArb, 0..2)37fun programArb(size: Int): Arb<Program> =38    bindsArb(size).map(::Program)39fun bindsArb(size: Int): Arb<Binds> {40    val inSize = min(size, 60)41    return Arb.map(keywordArb, lambdaFormArb(inSize), 1, max(size, 2)).map(::Binds)42}43fun lambdaFormArb(size: Int): Arb<LambdaForm> =44    Arb.bind(keywordsArb, keywordsArb, exprArb(size), ::LambdaForm)45// Arb.choice is too eager.46fun exprArb(size: Int): Arb<Expr> {47    val inSize: Int = size * 2 / 348    return Arb.int(1..6).flatMap {49        when (it) {50            1 -> letArb(inSize)51            2 -> caseArb(inSize)52            3 -> appFArb53            4 -> appCArb54            5 -> appPArb55            else -> litEArb  // weight towards simple literals.56        }57    }58}59fun letArb(size: Int): Arb<Expr.Let> =60    Arb.bind(bindsArb(size), exprArb(size), Expr::Let)61fun caseArb(size: Int): Arb<Expr.Case> =62    Arb.bind(exprArb(size), Arb.list(altArb(size), 0..3)) { expr, alts -> Expr.Case(expr, alts) }63val appFArb = Arb.bind(keywordArb, keywordsArb, Expr::AppF)64val appCArb = Arb.bind(keywordArb, keywordsArb, Expr::AppC)65val appPArb = Arb.bind(keywordArb, keywordArb, keywordArb, Expr::AppP)66val litEArb = Arb.int(-1000, 1000).map(Expr::LitE)67fun altArb(size: Int): Arb<Alt> =68    Arb.bind(keywordUcArb, keywordsArb, exprArb(size), ::Alt)69fun pretty(program: Program) : DocNo = pretty(program.binds)70fun pretty(binds: Binds): DocNo = align(vsep(71    binds.map.entries.map { (variable, lambdaForm) ->72        text(variable) spc text("=") spc pretty(lambdaForm)73    }74))75/*76instance Pretty LambdaForm where77    pretty (LambdaForm free bound body) = (prettyExp . (<+> "->") . prettyBound . prettyFree) "\\"78      where79        prettyFree | null free = id80                   | otherwise = (<> lparen <> hsep (map pretty free) <> rparen)81        prettyBound | null bound = id82                    | null free = (<> hsep (map pretty bound))83                    | otherwise = (<+> hsep (map pretty bound))84        prettyExp = (<+> pretty body)85 */86fun pretty(lambdaForm: LambdaForm): DocNo {87    fun prettyFree(node: DocNo): DocNo = if (lambdaForm.free.isEmpty()) {88        node cat lparen cat hsep(lambdaForm.free.map(::pretty)) cat rparen89    } else {90        node91    }92    fun prettyBound(node: DocNo): DocNo = when {93        lambdaForm.bound.isEmpty() -> node94        lambdaForm.free.isEmpty() -> node cat hsep(lambdaForm.bound.map(::pretty))95        else -> node spc hsep(lambdaForm.bound.map(::pretty))96    }97    fun prettyExp(node: DocNo): DocNo = node spc pretty(lambdaForm.body)98    fun arrow(node: DocNo): DocNo = node spc text("->")99    return prettyExp(arrow(prettyBound(prettyFree(text("\\")))))100}101/*instance Pretty Expr where102    pretty = \expr -> case expr of103        Let binds body ->104            align (vsep [ "let" <+> align (pretty binds)105                        , "in" <+> pretty body ])106        Case scrutinee alts -> vsep107            [ "case" <+> pretty scrutinee <+> "of"108            , indent 4 (align (vsep (map pretty alts))) ]109        AppF f [] -> pretty f110        AppF f args -> pretty f <+> hsep (map pretty args)111        AppC c [] -> pretty c112        AppC c args -> pretty c <+> hsep (map pretty args)113        AppP op x y -> pretty op <+> pretty x <+> pretty y114        LitE lit -> pretty lit115*/116fun pretty(expr: Expr): DocNo = when(expr) {117    is Expr.Let -> align(vsep(text("let") spc align(pretty(expr.binds)), text("in") spc pretty(expr.body)))118    is Expr.Case -> vsep(119        text("case") spc pretty(expr.scrutinee) spc text("of"),120        indent(4, align(vsep(expr.alts.map(::pretty))))121    )122    is Expr.AppF -> if(expr.args.isEmpty()) { pretty(expr.f) } else { pretty(expr.f) spc hsep(expr.args.map(::pretty)) }123    is Expr.AppC -> if(expr.args.isEmpty()) { pretty(expr.c) } else { pretty(expr.c) spc hsep(expr.args.map(::pretty)) }124    is Expr.AppP -> text(expr.op) spc text(expr.x) spc text(expr.y)125    is Expr.LitE -> pretty(expr.lit)126}127fun pretty(alt: Alt): DocNo = if(alt.args.isEmpty()) {128    pretty(alt.con) spc text("->") spc pretty(alt.body)129} else {130    pretty(alt.con) spc hsep(alt.args.map(::pretty)) spc text("->") spc pretty(alt.body)131}132/** QuickCheck has [a size parameter] but we want to limit the number of internal bindings to avoid stack overflow.133 * [a size parameter]: https://hackage.haskell.org/package/QuickCheck-2.14.2/docs/Test-QuickCheck.html#v:getSize134 */135fun randomProgram(rs: RandomSource, size: Int): Program {136    return programArb(size).next(rs=rs)137}138enum class RenderStyle(val render: (Doc<Nothing>) -> SDS<Nothing>) {139    Pretty8050({doc -> layoutPretty(Opts.std(80, 0.5), doc)}),140    Smart8050({doc -> layoutSmart(Opts.std(80, 0.5), doc) }),141    PrettyUnbound({doc -> layoutPretty(Opts.unbounded, doc) }),142    SmartUnbound({doc -> layoutSmart(Opts.unbounded, doc) }),143    Compact({doc -> layoutCompact(doc) }),144}145class CountSink<A> : SimpleSink<A> {146    var count = 0147    override fun openAnn(ann: A) {148    }149    override fun closeAnn(ann: A) {150    }151    override fun emit(cs: CharSequence) {152        count += cs.length153    }154}155data class Times(156    val build: Duration,157    val render: Duration,158    val sink: Duration,159    val count: Int160)161/**162 * There are dedicated benchmarking modules out there, but at this stage I want to see if we can render large documents163 * without falling over.164 */165class Benchmark {166    @OptIn(ExperimentalTime::class)167    fun benchmark(subject: Program, style: RenderStyle) {168        val doc: DocNo169        val buildTime = measureTime {170            doc = pretty(subject)171        }172        val docStream: SDS<Nothing>173        val renderTime = measureTime {174            docStream = style.render(doc)175        }176        val counter = CountSink<Nothing>()177        val sinkTime = measureTime {178            counter.render(docStream)179        }180        // println(AppendableSink<Nothing>().toString(docStream))181        println(Times(buildTime, renderTime, sinkTime, counter.count))182    }183    @Test184    fun benchmark60Compact() {185        benchmark(p60, RenderStyle.Compact)186    }187    @Test188    fun benchmark60Pretty8050() {189        benchmark(p60, RenderStyle.Pretty8050)190    }191    @Test192    fun benchmark60Smart8050() {193        benchmark(p60, RenderStyle.Smart8050)194    }195    @Test196    fun benchmark60PrettyUnbound() {197        benchmark(p60, RenderStyle.PrettyUnbound)198    }199    @Test200    fun benchmark60SmartUnbound() {201        benchmark(p60, RenderStyle.SmartUnbound)202    }203    @Test204    fun benchmark120Compact() {205        benchmark(p120, RenderStyle.Compact)206    }207    @Test208    fun benchmark120Pretty8050() {209        benchmark(p120, RenderStyle.Pretty8050)210    }211    @Test212    fun benchmark120Smart8050() {213        benchmark(p120, RenderStyle.Smart8050)214    }215    @Test216    fun benchmark120PrettyUnbound() {217        benchmark(p120, RenderStyle.PrettyUnbound)218    }219    @Test220    fun benchmark120SmartUnbound() {221        benchmark(p120, RenderStyle.SmartUnbound)222    }223    @Test224    fun benchmark240Compact() {225        benchmark(p240, RenderStyle.Compact)226    }227    @Test228    fun benchmark240Pretty8050() {229        benchmark(p240, RenderStyle.Pretty8050)230    }231    @Test232    fun benchmark240Smart8050() {233        benchmark(p240, RenderStyle.Smart8050)234    }235    @Test236    fun benchmark240PrettyUnbound() {237        benchmark(p240, RenderStyle.PrettyUnbound)238    }239    @Test240    fun benchmark240SmartUnbound() {241        benchmark(p240, RenderStyle.SmartUnbound)242    }243    244    @Test245    fun benchmark480Compact() {246        benchmark(p480, RenderStyle.Compact)247    }248    @Test249    fun benchmark480Pretty8050() {250        benchmark(p480, RenderStyle.Pretty8050)251    }252    @Test253    fun benchmark480Smart8050() {254        benchmark(p480, RenderStyle.Smart8050)255    }256    @Test257    fun benchmark480PrettyUnbound() {258        benchmark(p480, RenderStyle.PrettyUnbound)259    }260    @Test261    fun benchmark480SmartUnbound() {262        benchmark(p480, RenderStyle.SmartUnbound)263    }264    companion object {265        private val p60 = randomProgram(RandomSource.seeded(1L), 60)266        private val p120 = randomProgram(RandomSource.seeded(1L), 120)267        private val p240 = randomProgram(RandomSource.seeded(1L), 240)268        private val p480 = randomProgram(RandomSource.seeded(1L), 480)269    }270}...predef-test.kt
Source:predef-test.kt  
1package arrow.fx.coroutines.stream2import arrow.core.Either3import arrow.core.identity4import arrow.fx.coroutines.CancelToken5import arrow.fx.coroutines.ExitCase6import arrow.fx.coroutines.ForkAndForget7import arrow.fx.coroutines.Promise8import arrow.fx.coroutines.Resource9import arrow.fx.coroutines.guaranteeCase10import io.kotest.property.Arb11import io.kotest.property.arbitrary.constant12import arrow.core.left13import arrow.core.right14import arrow.fx.coroutines.Environment15import io.kotest.assertions.fail16import io.kotest.matchers.Matcher17import io.kotest.matchers.MatcherResult18import io.kotest.matchers.types.shouldBeInstanceOf19import io.kotest.property.arbitrary.bind20import io.kotest.property.arbitrary.char21import io.kotest.property.arbitrary.choice22import io.kotest.property.arbitrary.int23import io.kotest.property.arbitrary.long24import io.kotest.property.arbitrary.map25import io.kotest.property.arbitrary.string26import kotlinx.atomicfu.atomic27import kotlinx.coroutines.Dispatchers28import java.io.ByteArrayOutputStream29import java.io.OutputStream30import java.io.PrintStream31import java.nio.charset.StandardCharsets32import java.util.concurrent.ThreadFactory33import kotlin.coroutines.Continuation34import kotlin.coroutines.CoroutineContext35import kotlin.coroutines.EmptyCoroutineContext36import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn37import kotlin.coroutines.intrinsics.intercepted38import kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED39import kotlin.coroutines.resume40import kotlin.coroutines.resumeWithException41import kotlin.coroutines.startCoroutine42data class SideEffect(var counter: Int = 0) {43  fun increment() {44    counter++45  }46}47val singleThreadName = "single"48val single = Resource.singleThreadContext(singleThreadName)49val threadName: suspend () -> String =50  { Thread.currentThread().name }51class NamedThreadFactory(private val mkName: (Int) -> String) : ThreadFactory {52  private val count = atomic(0)53  override fun newThread(r: Runnable): Thread =54    Thread(r, mkName(count.value))55      .apply { isDaemon = true }56}57fun unsafeEquals(other: CancelToken): Matcher<CancelToken> = object : Matcher<CancelToken> {58  val env = Environment(EmptyCoroutineContext)59  override fun test(value: CancelToken): MatcherResult {60    val r1 = env.unsafeRunSync { value.cancel.invoke() }61    val r2 = env.unsafeRunSync { other.cancel.invoke() }62    return MatcherResult(r1 == r2, "Expected: $r2 but found: $r1", "$r2 and $r1 should be equal")63  }64}65suspend fun assertCancellable(f: suspend () -> Unit): Unit {66  val p = Promise<ExitCase>()67  val start = Promise<Unit>()68  val fiber = ForkAndForget {69    guaranteeCase(70      fa = {71        start.complete(Unit)72        f()73      },74      finalizer = { ex -> p.complete(ex) }75    )76  }77  start.get()78  fiber.cancel()79  p.get().shouldBeInstanceOf<ExitCase.Cancelled>()80}81/**82 * Catches `System.err` output, for testing purposes.83 */84fun catchSystemErr(thunk: () -> Unit): String {85  val outStream = ByteArrayOutputStream()86  catchSystemErrInto(outStream, thunk)87  return String(outStream.toByteArray(), StandardCharsets.UTF_8)88}89/**90 * Catches `System.err` output into `outStream`, for testing purposes.91 */92@Synchronized93fun <A> catchSystemErrInto(outStream: OutputStream, thunk: () -> A): A {94  val oldErr = System.err95  val fakeErr = PrintStream(outStream)96  System.setErr(fakeErr)97  return try {98    thunk()99  } finally {100    System.setErr(oldErr)101    fakeErr.close()102  }103}104fun Arb.Companion.throwable(): Arb<Throwable> =105  Arb.string().map(::RuntimeException)106fun <A> Arb.Companion.result(right: Arb<A>): Arb<Result<A>> {107  val failure: Arb<Result<A>> = Arb.throwable().map { e -> Result.failure<A>(e) }108  val success: Arb<Result<A>> = right.map { a -> Result.success(a) }109  return Arb.choice(failure, success)110}111fun <L, R> Arb.Companion.either(left: Arb<L>, right: Arb<R>): Arb<Either<L, R>> {112  val failure: Arb<Either<L, R>> = left.map { l -> l.left() }113  val success: Arb<Either<L, R>> = right.map { r -> r.right() }114  return Arb.choice(failure, success)115}116fun Arb.Companion.intRange(min: Int = Int.MIN_VALUE, max: Int = Int.MAX_VALUE): Arb<IntRange> =117  Arb.bind(Arb.int(min, max), Arb.int(min, max)) { a, b ->118    if (a < b) a..b else b..a119  }120fun Arb.Companion.longRange(min: Long = Long.MIN_VALUE, max: Long = Long.MAX_VALUE): Arb<LongRange> =121  Arb.bind(Arb.long(min, max), Arb.long(min, max)) { a, b ->122    if (a < b) a..b else b..a123  }124fun Arb.Companion.charRange(): Arb<CharRange> =125  Arb.bind(Arb.char(), Arb.char()) { a, b ->126    if (a < b) a..b else b..a127  }128fun <O> Arb.Companion.function(arb: Arb<O>): Arb<() -> O> =129  arb.map { { it } }130fun Arb.Companion.unit(): Arb<Unit> =131  Arb.constant(Unit)132/** Useful for testing success & error scenarios with an `Either` generator **/133internal fun <A> Either<Throwable, A>.rethrow(): A =134  fold({ throw it }, ::identity)135internal fun <A> Result<A>.toEither(): Either<Throwable, A> =136  fold({ a -> Either.Right(a) }, { e -> Either.Left(e) })137internal suspend fun Throwable.suspend(): Nothing =138  suspendCoroutineUninterceptedOrReturn { cont ->139    suspend { throw this }.startCoroutine(140      Continuation(Dispatchers.Default) {141        cont.intercepted().resumeWith(it)142      }143    )144    COROUTINE_SUSPENDED145  }146internal suspend fun <A> A.suspend(): A =147  suspendCoroutineUninterceptedOrReturn { cont ->148    suspend { this }.startCoroutine(149      Continuation(Dispatchers.Default) {150        cont.intercepted().resumeWith(it)151      }152    )153    COROUTINE_SUSPENDED154  }155internal fun <A> A.suspended(): suspend () -> A =156  suspend { suspend() }157internal suspend fun <A> Either<Throwable, A>.suspend(): A =158  suspendCoroutineUninterceptedOrReturn { cont ->159    suspend { this }.startCoroutine(160      Continuation(Dispatchers.Default) {161        it.fold(162          {163            it.fold(164              { e -> cont.intercepted().resumeWithException(e) },165              { a -> cont.intercepted().resume(a) }166            )167          },168          { e -> cont.intercepted().resumeWithException(e) }169        )170      }171    )172    COROUTINE_SUSPENDED173  }174internal fun <A> Either<Throwable, A>.suspended(): suspend () -> A =175  suspend { suspend() }176/**177 * Example usage:178 * ```kotlin179 * val exception = assertThrows<IllegalArgumentException> {180 *     throw IllegalArgumentException("Talk to a duck")181 * }182 * assertEquals("Talk to a duck", exception.message)183 * ```184 * @see Assertions.assertThrows185 */186inline fun <A> assertThrowable(executable: () -> A): Throwable {187  val a = try {188    executable.invoke()189  } catch (e: Throwable) {190    e191  }192  return if (a is Throwable) a else fail("Expected an exception but found: $a")193}194internal suspend fun CoroutineContext.shift(): Unit =195  suspendCoroutineUninterceptedOrReturn { cont ->196    suspend { this }.startCoroutine(197      Continuation(this) {198        cont.resume(Unit)199      }200    )201    COROUTINE_SUSPENDED202  }...DynamicAddressEndpointsTest.kt
Source:DynamicAddressEndpointsTest.kt  
...21@TestInstance(TestInstance.Lifecycle.PER_CLASS)22internal class DynamicAddressEndpointsTest {23    @Test24    suspend fun `dynamicAddressEndpoint WHEN property changed THEN requests are targeted to other address`() {25        val (mockServer1, mockServer1RequestsCounter) = createMockServerWithRequestsCount()26        val (mockServer2, mockServer2RequestsCounter) = createMockServerWithRequestsCount()27        try {28            listOf(29                mockServer1.launchStart(),30                mockServer2.launchStart()31            ).joinAll()32            val mockServer1Address = mockServer1.httpUri().asSocketAddress()33            val mockServer2Address = mockServer2.httpUri().asSocketAddress()34            val dynamicAddressProp = AtomicProperty<SocketAddress>(mockServer1Address)35            val dynamicAddressEndpoint = DynamicAddressEndpoints.dynamicAddressEndpoint(dynamicAddressProp)36            val client = WebClient.builder(SessionProtocol.HTTP, dynamicAddressEndpoint).build()37            client.makeCountedRequest().await()38            mockServer1RequestsCounter.get() shouldBe 139            mockServer2RequestsCounter.get() shouldBe 040            dynamicAddressProp.set(mockServer2Address)41            client.makeCountedRequest().await()42            mockServer1RequestsCounter.get() shouldBe 143            mockServer2RequestsCounter.get() shouldBe 144            dynamicAddressProp.set(mockServer1Address)45            client.makeCountedRequest().await()46            mockServer1RequestsCounter.get() shouldBe 247            mockServer2RequestsCounter.get() shouldBe 148        } finally {49            listOf(50                mockServer1.launchStop(),51                mockServer2.launchStop()52            ).joinAll()53        }54    }55    @Test56    suspend fun `dynamicAddressListEndpointGroup WHEN property changed THEN requests are targeted to other addresses`() {57        val (mockServer1, mockServer1RequestsCounter) = createMockServerWithRequestsCount()58        val (mockServer2, mockServer2RequestsCounter) = createMockServerWithRequestsCount()59        val (mockServer3, mockServer3RequestsCounter) = createMockServerWithRequestsCount()60        fun assertRequestCounters(61            expectedMockServer1RequestsCounter: Int,62            expectedMockServer2RequestsCounter: Int,63            expectedMockServer3RequestsCounter: Int64        ) {65            mockServer1RequestsCounter.get() shouldBe expectedMockServer1RequestsCounter66            mockServer2RequestsCounter.get() shouldBe expectedMockServer2RequestsCounter67            mockServer3RequestsCounter.get() shouldBe expectedMockServer3RequestsCounter68        }69        try {70            listOf(71                mockServer1.launchStart(),72                mockServer2.launchStart(),73                mockServer3.launchStart()74            ).joinAll()75            val mockServer1Address = mockServer1.httpUri().asSocketAddress()76            val mockServer2Address = mockServer2.httpUri().asSocketAddress()77            val mockServer3Address = mockServer3.httpUri().asSocketAddress()78            val dynamicAddressListProp = AtomicProperty<List<SocketAddress>>(79                listOf(80                    mockServer1Address81                )82            )83            val dynamicAddressListEndpointGroup = DynamicAddressEndpoints.dynamicAddressListEndpointGroup(84                dynamicAddressListProp85            )86            val client = WebClient.builder(SessionProtocol.HTTP, dynamicAddressListEndpointGroup).build()87            List(2) {88                client.makeCountedRequest()89            }.awaitAll()90            assertRequestCounters(2, 0, 0)91            dynamicAddressListProp.set(listOf(mockServer2Address, mockServer3Address))92            List(2) {93                client.makeCountedRequest()94            }.awaitAll()95            assertRequestCounters(2, 1, 1)96            dynamicAddressListProp.set(listOf(mockServer1Address, mockServer3Address))97            List(2) {98                client.makeCountedRequest()99            }.awaitAll()100            assertRequestCounters(3, 1, 2)101            dynamicAddressListProp.set(emptyList())102            val thrownException = shouldThrowExactly<UnprocessedRequestException> {103                client.makeCountedRequest().await()104            }105            thrownException.shouldHaveCauseInstanceOf<EmptyEndpointGroupException>()106        } finally {107            listOf(108                mockServer1.launchStop(),109                mockServer2.launchStop(),110                mockServer3.launchStop()111            ).joinAll()112        }113    }114    companion object {115        const val COUNTED_PATH = "/counted"116        fun URI.asSocketAddress(): SocketAddress = SocketAddress(this.host, this.port)117        fun WebClient.makeCountedRequest(): Deferred<*> = get(COUNTED_PATH).aggregate().asDeferred()118        fun createMockServerWithRequestsCount(): Pair<ArmeriaMockServer, AtomicInteger> {119            val requestsCounter = AtomicInteger(0)120            val mockServer = ArmeriaMockServer {121                service(COUNTED_PATH) { _, _ ->122                    requestsCounter.incrementAndGet()123                    HttpResponse.of(HttpStatus.OK)124                }125            }126            return mockServer to requestsCounter127        }128    }129}...SystemPropertyFiltersTests.kt
Source:SystemPropertyFiltersTests.kt  
...13import io.kotest.matchers.collections.shouldContainExactly14import io.kotest.matchers.shouldBe15import kotlin.reflect.KClass16private val executed = mutableListOf<String>()17internal fun TestScope.testAndIncrementCounter() {18   1 shouldBe 1 // fake assertion so tests don't fail from fail on no assertion setting if it's set19   executed.add(this.testCase.name.testName)20}21private fun numberOfTestsRunShouldBe(expected: Int) {22   executed.size shouldBe expected23}24private fun testsRunShouldBe(vararg name: String) {25   executed shouldContainExactly name.toList()26}27private val testSuite = listOf<KClass<out Spec>>(28   DistantFutureSciFiTests::class,29   NearFutureSciFiTests::class,30   BarTests::class,31   FooTests::class,32)33/**34 * Test that the filter expressions in [KotestEngineProperties.filterTests] and35 * [KotestEngineProperties.filterSpecs] work similarly to how gradle filters in --tests described in36 * https://docs.gradle.org/current/userguide/java_testing.html#full_qualified_name_pattern37 */38@KotestInternal39@Isolate40class SystemPropertyTestFiltersTests : FunSpec({41   beforeTest {42      executed.clear()43   }44   test("include all classes when filter specs is blank") {45      withSystemProperties(46         mapOf(47            KotestEngineProperties.filterSpecs to "",48            KotestEngineProperties.filterTests to ""49         )50      ) { TestEngineLauncher().withClasses(testSuite).withConfiguration(ProjectConfiguration()).launch() }51      numberOfTestsRunShouldBe(13)52   }53   test("filters a specific class") {54      withSystemProperties(55         mapOf(56            KotestEngineProperties.filterSpecs to "*DistantFutureSciFiTests",57            KotestEngineProperties.filterTests to ""58         )59      ) { TestEngineLauncher().withClasses(testSuite).withConfiguration(ProjectConfiguration()).launch() }60      numberOfTestsRunShouldBe(7)61   }62   test("filters a class prefix") {63      withSystemProperties(64         mapOf(65            KotestEngineProperties.filterSpecs to "*FutureSciFiTests",66            KotestEngineProperties.filterTests to ""67         )68      ) { TestEngineLauncher().withClasses(testSuite).withConfiguration(ProjectConfiguration()).launch() }69      numberOfTestsRunShouldBe(9)70   }71   test("filters a specific class and test") {72      withSystemProperties(73         mapOf(74            KotestEngineProperties.filterSpecs to "*NearFutureSciFiTests",75            KotestEngineProperties.filterTests to "Daedalus*"76         )77      ) { TestEngineLauncher().withClasses(testSuite).withConfiguration(ProjectConfiguration()).launch() }78      numberOfTestsRunShouldBe(1)79   }80   test("filters a test name with spaces") {81      withSystemProperties(82         mapOf(83            KotestEngineProperties.filterSpecs to "",84            KotestEngineProperties.filterTests to "trek tests*"85         )86      ) { TestEngineLauncher().withClasses(testSuite).withConfiguration(ProjectConfiguration()).launch() }87      numberOfTestsRunShouldBe(3)88   }89   test("filters all classes in a package") {90      withSystemProperties(91         mapOf(92            KotestEngineProperties.filterSpecs to "com.sksamuel.kotest.engine.interceptors.filters1.*",93            KotestEngineProperties.filterTests to ""94         )95      ) { TestEngineLauncher().withClasses(testSuite).withConfiguration(ProjectConfiguration()).launch() }96      numberOfTestsRunShouldBe(2)97   }98   test("filters nested tests in a context") {99      withSystemProperties(100         mapOf(101            KotestEngineProperties.filterSpecs to "",102            KotestEngineProperties.filterTests to "expanse tests*"103         )104      ) { TestEngineLauncher().withClasses(testSuite).withConfiguration(ProjectConfiguration()).launch() }105      numberOfTestsRunShouldBe(4)106   }107   test("filter tests using prefix and suffix wildcard") {108      withSystemProperties(109         mapOf(110            KotestEngineProperties.filterSpecs to "",111            KotestEngineProperties.filterTests to "*anse tes*"112         )113      ) { TestEngineLauncher().withClasses(testSuite).withConfiguration(ProjectConfiguration()).launch() }114      numberOfTestsRunShouldBe(4)115   }116   test("filter tests with prefix wildcard") {117      withSystemProperties(118         mapOf(119            KotestEngineProperties.filterSpecs to "",120            KotestEngineProperties.filterTests to "*BC-304"121         )122      ) { TestEngineLauncher().withClasses(testSuite).withConfiguration(ProjectConfiguration()).launch() }123      numberOfTestsRunShouldBe(2)124      testsRunShouldBe("Daedalus BC-304", "Odyssey BC-304")125   }126})127private class DistantFutureSciFiTests : FunSpec({128   context("trek tests") {129      test("Enterprise NCC-1701") { testAndIncrementCounter() }130      test("Excelsior NCC-2000") { testAndIncrementCounter() }131      test("Defiant NX-74205") { testAndIncrementCounter() }132   }133   context("expanse tests") {134      test("MCRN Donnager") { testAndIncrementCounter() }135      test("Rocinante") { testAndIncrementCounter() }136      test("UNN Arboghast") { testAndIncrementCounter() }137      test("UNN Agatha King") { testAndIncrementCounter() }138   }139})140private class NearFutureSciFiTests : FunSpec({141   test("Daedalus BC-304") { testAndIncrementCounter() }142   test("Odyssey BC-304") { testAndIncrementCounter() }143})...BoardFacadeTest.kt
Source:BoardFacadeTest.kt  
...91    }92    @Test93    fun `edit board`() {94        val original =95            db.insert(board(label = "r", postCounter = 1L, settings = boardSettings(nsfw = false)))96        val editForm =97            original.toForm().apply { name = "Updated name"; boardSettingsForm = boardSettings(nsfw = true).toForm() }98        val updated = boardFacade.editBoard(original.toDto(), editForm)99        updated.label shouldBe original.label100        updated.name shouldBe editForm.name101        updated.settings.isNsfw shouldBe true102    }103    @Test104    fun `delete board`() {105        val board = db.insert(board(label = "r"))106        db.select(board).shouldBePresent()107        boardFacade.deleteBoard(board.toDto())108        db.select(board).shouldBeEmpty()109    }...shrink.kt
Source:shrink.kt  
...21   mode: ShrinkingMode,22   test: suspend (A) -> Unit23): ShrinkResult<A> {24   if (initial.isEmpty()) return ShrinkResult(initial.value(), initial.value(), null)25   val counter = Counter()26   val tested = mutableSetOf<A>()27   val sb = StringBuilder()28   sb.append("Attempting to shrink arg ${initial.value().print().value}\n")29   val stepResult = doStep(initial, mode, tested, counter, test, sb)30   result(sb, stepResult, counter.count)31   return if (stepResult == null) {32      ShrinkResult(initial.value(), initial.value(), null)33   } else {34      ShrinkResult(initial.value(), stepResult.failed, stepResult.cause)35   }36}37class Counter {38   var count = 039   fun inc() = count++40}41/**42 * The result of shrinking a failed arg.43 * If no shrinking took place, shrink should be set to the same as iniital44 */45data class ShrinkResult<out A>(val initial: A, val shrink: A, val cause: Throwable?)46data class StepResult<A>(val failed: A, val cause: Throwable)47/**48 * Performs shrinking on the given RTree. Recurses into the tree for failing cases.49 * Returns the last candidate to fail as a [StepResult] or null if the initial passes.50 */51suspend fun <A> doStep(52   tree: RTree<A>,53   mode: ShrinkingMode,54   tested: MutableSet<A>,55   counter: Counter,56   test: suspend (A) -> Unit,57   sb: StringBuilder58): StepResult<A>? {59   // if no more shrinking return null (if we've hit the bounds)60   if (!mode.isShrinking(counter.count)) return null61   val candidates = tree.children.value62   candidates.asSequence()63      // shrinkers might generate duplicate candidates so we must filter them out to avoid infinite loops or slow shrinking64      .filter { tested.add(it.value()) }65      .forEach { a ->66         val candidate = a.value()67         counter.inc()68         try {69            test(candidate)...Counter
Using AI Code Generation
1    val counter = Counter()2    forAll(100, Gen.int()) { i ->3        counter.increment()4    }5    val counter = Counter()6    forAll(100, Gen.int()) { i ->7        counter.increment()8    }9}10data class User(val name: String, val age: Int)11fun User.isAdult() = age >= 1812fun User.isNotAdult() = !isAdult()13fun main() {14    forAll(100, Gen.int()) { i ->15    }16    forAll(100, Gen.int()) { i ->17    }18    forAll(100, Gen.int()) { i ->19    }20}21data class User(val name: String, val age: Int)22fun User.isAdult() = age >= 1823fun User.isNotAdult() = !isAdult()24fun main() {25    forAll(100, Gen.int()) { i ->26    }27    forAll(100, Gen.int()) { i ->28    }29    forAll(100, Gen.int()) { i ->30    }31}32data class User(val name: String, val age: Int)33fun User.isAdult() = age >= 1834fun User.isNotAdult() = !isAdult()35fun main() {36    forAll(100, Gen.int()) { i ->37    }38    forAll(100, Gen.int()) { i ->39    }40    forAll(100, Gen.int()) { i ->41    }42}43data class User(val name: String, val age: Int)44fun User.isAdult() = age >= 1845fun User.isNotAdult() = !isAdult()46fun main() {47    forAll(100, Gen.int()) { i ->48    }49    forAll(100, Gen.int()) { i ->50    }51    forAll(100, Gen.int()) { i ->52    }53}54data class User(val name: StringCounter
Using AI Code Generation
1    internal class Counter {2        fun increment() {3        }4    }5    class MyTest : FunSpec() {6        init {7            test("counter test") {8                val counter = Counter()9                counter.increment()10                counter.increment()11            }12        }13    }Counter
Using AI Code Generation
1val counter = Counter()2counter.inc()3counter.dec()4val counter = Counter()5counter.inc()6counter.dec()7val counter = Counter()8counter.inc()9counter.dec()10val counter = Counter()11counter.inc()12counter.dec()13val counter = Counter()14counter.inc()15counter.dec()16val counter = Counter()17counter.inc()18counter.dec()19val counter = Counter()20counter.inc()21counter.dec()22val counter = Counter()23counter.inc()24counter.dec()25val counter = Counter()26counter.inc()27counter.dec()28val counter = Counter()29counter.inc()30counter.dec()31val counter = Counter()32counter.inc()Counter
Using AI Code Generation
1    val counter = Counter()2    val property = forAll { i: Int ->3      counter.increment()4    }5    checkAll(property, 1000)6    val counter = Counter()7    val property = forAll { i: Int ->8      counter.increment()9    }10    checkAll(property, 1000)11    val counter = Counter()12    val property = forAll { i: Int ->13      counter.increment()14    }15    checkAll(property, 1000)16    val counter = Counter()17    val property = forAll { i: Int ->18      counter.increment()19    }20    checkAll(property, 1000)21    val counter = Counter()22    val property = forAll { i: Int ->23      counter.increment()24    }25    checkAll(property, 1000)26    val counter = Counter()27    val property = forAll { i: Int ->28      counter.increment()29    }30    checkAll(property, 1000)31    val counter = Counter()32    val property = forAll { i: Int ->33      counter.increment()34    }35    checkAll(property, 1000)36    val counter = Counter()37    val property = forAll { i: Int ->38      counter.increment()39    }40    checkAll(property, 1000)Counter
Using AI Code Generation
1val counter = Counter()2val counter2 = Counter()3val property = PropertyTesting.defaultIterationCount(1000).forAll<Int> { x ->4  counter.increment()5  counter2.increment()6}7property.check()8println("counter = $counter")9println("counter2 = $counter2")10val counter = Counter()11val counter2 = Counter()12val property = PropertyTesting.defaultIterationCount(1000).forAll<Int> { x ->13  counter.increment()14  counter2.increment()15}16property.check()17println("counter = $counter")18println("counter2 = $counter2")19val counter = Counter()20val counter2 = Counter()21val property = PropertyTesting.defaultIterationCount(1000).forAll<Int> { x ->22  counter.increment()23  counter2.increment()24}25property.check()26println("counter = $counter")27println("counter2 = $counter2")28val counter = Counter()29val counter2 = Counter()30val property = PropertyTesting.defaultIterationCount(1000).forAll<Int> { x ->31  counter.increment()32  counter2.increment()33}34property.check()35println("counter = $counter")36println("counter2 = $counter2")37val counter = Counter()38val counter2 = Counter()39val property = PropertyTesting.defaultIterationCount(1000).forAll<Int> { x ->40  counter.increment()41  counter2.increment()42}43property.check()44println("counter = $counter")45println("counter2 = $counter2")Counter
Using AI Code Generation
1private val counter = Counter()2private fun <T> PropertyTesting<T>.counter() = this.apply {3afterTest { counter.increment() }4}5private val counter = Counter()6private fun <T> PropertyTesting<T>.counter() = this.apply {7afterTest { counter.increment() }8}9fun `test 1`() {10}11fun `test 2`() {12}13fun `test 3`() {14}15fun `test 4`() {16}17fun `test 5`() {18}19fun `test 6`() {20}21fun `test 7`() {22}23fun `test 8`() {24}25fun `test 9`() {26}27fun `test 10`() {28}29fun `test 11`() {30}31fun `test 12`() {32}33fun `test 13`() {34}35fun `test 14`() {36}37fun `test 15`() {38}39fun `test 16`() {40}41fun `test 17`() {42}43fun `test 18`() {44}45fun `test 19`() {46}47fun `test 20`() {48}49fun `test 21`() {50}51fun `test 22`() {52}53fun `test 23`() {54}55fun `test 24`() {56}57fun `test 25`() {58}59fun `test 26`() {60}61fun `test 27`() {62}63fun `test 28`() {64}Counter
Using AI Code Generation
1     val counter = Counter()2     val random = Random(counter)3     val randomInt = random.nextInt()4     println("randomInt: $randomInt")5     println("counter: $counter")6}7    counter: Counter(count=1)Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
