How to make virtual time pass in a test in Cats Effect 3?
Asked Answered
B

2

13

I am trying to convert Mules to Cats Effect 3 (CE3). Since it is a caching library, in its tests it needs (virtual) time to pass to test whether items will be expired. It is currently making fairly heavy use of cats.effect.laws.util.TestContext, which allows advancing the virtual clock without actually sleeping via tick. TestContext does not (as far as I have been able to discover) exist in CE3, but I am always loathe to puts sleep calls into a test. Rolling my own IO for this specific case though is a daunting prospect; surely this is a more general problem people have. I was not able to find a reference to TestContext in the migration guide, however.

Is there a known upgrade path for this case?

Batten answered 18/5, 2021 at 17:52 Comment(0)
A
5

As mentioned by Victor in comments about v3.3.0, this version is released about a day ago and you can see examples for virtual time in Mocking time paragraph in docs

Acerose answered 1/12, 2021 at 6:21 Comment(0)
B
6

With some help from Chris Davenport on Discord, I found that TestContext is still there, but has been moved from cats.effect.laws.util to cats.effect.kernel.testkit. It lives in its own project and artifact, so you will need to add a dependency (SBT syntax):

    "org.typelevel" %% "cats-effect-kernel-testkit" % catsEffectV % Test,

Also if you were not using anything else from the laws package than you will want to remove that dependency, which would look something like:

    "org.typelevel" %% "cats-effect-laws"           % catsEffectV % Test,

Presumably this is why they moved it: because it is not specific to laws.


However, I was not successful in getting virtual time to pass in my tests with this, and have sadly brute-forced it with IO.sleeps for now. :/

Batten answered 18/5, 2021 at 19:17 Comment(2)
Sadly, TestContext doc seems outdated for 3.x CE -- it has no timer method no more (timer is replaced with Temporal, per docs). I'm new to CE, so wondering which API could be used here.Styracaceous
Also, github.com/typelevel/cats-effect/issues/2220 Sadly, this is scheduled for 3.3.0Styracaceous
A
5

As mentioned by Victor in comments about v3.3.0, this version is released about a day ago and you can see examples for virtual time in Mocking time paragraph in docs

Acerose answered 1/12, 2021 at 6:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.