Last active
June 10, 2020 15:39
-
-
Save Daenyth/cc684f9b9f485f3dfd04d22ef72e99d1 to your computer and use it in GitHub Desktop.
DoobieTest scalatest helper for doobie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cats.effect.{Blocker, ContextShift, IO} | |
import doobie.util.testing.Analyzable | |
import doobie.util.transactor.Transactor | |
import org.scalactic.source | |
import org.scalatest.Succeeded | |
import org.scalatest.funspec.AsyncFunSpecLike | |
import scala.concurrent.{ExecutionContext, Future} | |
trait DoobieTest extends AsyncFunSpecLike with doobie.scalatest.IOChecker { | |
/** We need a non-single-threaded EC in order to run doobie `check()` tests, otherwise they will deadlock */ | |
protected def multithreadedExecutionContext: ExecutionContext | |
protected def registerCheck[A: Analyzable](name: String, statement: A)( | |
implicit pos: source.Position | |
): Unit = | |
registerAsyncTest(s"check($name)") { | |
implicit val executionContext: ExecutionContext = | |
multithreadedExecutionContext | |
Future(scala.concurrent.blocking(check(statement))).map(_ => Succeeded) | |
} | |
override protected val it = new ItWord | |
protected class ItWord extends super.ItWord { | |
/** Register a doobie `check()` test | |
* | |
* @tparam A Something that can be `check()`ed, like a [[doobie.Query0]] or [[doobie.Update0]] | |
* @see [[https://tpolecat.github.io/doobie/docs/13-Unit-Testing.html Doobie Unit Testing]] | |
* @example {{{ | |
* it checksQuery "queryName" -> myQuery | |
* }}} | |
* */ | |
def checksQuery[A: Analyzable]( | |
nameAndStatement: (String, A) | |
)(implicit pos: source.Position): Unit = | |
registerCheck(nameAndStatement._1, nameAndStatement._2) | |
} | |
} | |
trait DoobieSlickTest { | |
def transactorFromSlick( | |
slickDb: slick.jdbc.JdbcBackend#Database, | |
connectEc: ExecutionContext, | |
blocker: Blocker | |
)( | |
implicit CS: ContextShift[IO] | |
): Option[Transactor[IO]] = { | |
val jdbcSource = slickDb.source match { | |
case s: slick.jdbc.hikaricp.HikariCPJdbcDataSource => Some(s.ds) | |
case s: slick.jdbc.DataSourceJdbcDataSource => Some(s.ds) | |
case _ => None | |
} | |
jdbcSource.map(Transactor.fromDataSource[IO](_, connectEc, blocker)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment