Comments (6)
Yep, I had the same issue with both Mysql and Postgres. The problem that is log entry "database system is ready to accept connections" (for mysql case) doesn't actually mean that you can connect straight away. So I've got an extended version:
trait HasMysqlDatabase extends DockerTestKit with DockerMysqlService with BeforeAndAfterEach {
self: Suite =>
var mysqldb: Database = _
def bootstrapSchema: Option[DefaultMySQLDriver.DDL] = None
private val mysqlInitPc = PatienceConfig(Span(5, Seconds), Span(10, Millis))
private def initDb(port: Int) = {
val dbConfig =
s"""
|main = {
| connectionPool = "HikariCP"
| dataSourceClass = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
| properties = {
| url = "jdbc:mysql://${dockerExecutor.host}:$port/$MysqlDatabase",
| user = "$MysqlUser"
| password = "$MysqlPassword"
| }
| numThreads = 2
|}
""".stripMargin
val db = Database.forConfig("main", ConfigFactory.parseString(dbConfig))
RetryUtils.looped({
db.run(sql"select 1".as[Int])
}, 5, FiniteDuration(500, TimeUnit.MILLISECONDS)).map(_ => db)
}
override def beforeAll(): Unit = {
super.beforeAll()
val port = mysqlContainer.getPorts().futureValue(mysqlInitPc).apply(MysqlAdvertisedPort)
mysqldb = initDb(port).futureValue(mysqlInitPc)
}
override protected def beforeEach(): Unit = {
super.beforeEach()
bootstrapSchema.foreach { schema =>
mysqldb.run(schema.create).futureValue(mysqlInitPc)
}
}
override protected def afterEach(): Unit = {
try {
bootstrapSchema.foreach { schema =>
mysqldb.run(schema.drop).futureValue(mysqlInitPc)
}
} finally {
super.afterEach()
}
}
override def afterAll(): Unit = {
Try(mysqldb.close())
super.afterAll()
}
}
from docker-it-scala.
I don't want to make the sample project to depend on Slick, but if somebody want to implement this with plain jdbc and send a PR, they are more than welcome
from docker-it-scala.
I created even simpler PostgresReadyChecker with pure java/scala libraries (only org.postgresql.Driver needs to be on path)
import java.sql.DriverManager
import com.whisk.docker.{DockerCommandExecutor, DockerContainerState, DockerReadyChecker}
import scala.concurrent.ExecutionContext
import scala.util.Try
class PostgresReadyChecker(dbname: String, username: String, password: String) extends DockerReadyChecker {
override def apply(container: DockerContainerState)(implicit docker: DockerCommandExecutor, ec: ExecutionContext) =
container.getPorts().map(x => x.values.head).map(port =>
Try {
Class.forName("org.postgresql.Driver")
val connection = DriverManager.getConnection(s"jdbc:postgresql://${docker.host}:$port/$dbname", username, password)
if (connection != null) {
connection.close()
true
} else {
false
}
}.getOrElse(false)
)
And then it can be used as loped checker
val postgresContainer = DockerContainer("postgres:9.5")
.withPorts((5432, Some(PostgresAdvertisedPort)))
.withEnv(s"POSTGRES_USER=${db.getString("user")}", s"POSTGRES_PASSWORD=${db.getString("password")}")
.withReadyChecker(
new PostgresReadyChecker(DbName, db.getString("user"), db.getString("password")).looped(10, 1 second)
)
Usually after 6-7 seconds it is started.
Code is here
https://github.com/fokot/docker-scala/blob/master/src/test/scala/fokot/docker/scala/service/PostgresReadyChecker.scala
and here
https://github.com/fokot/docker-scala/blob/master/src/test/scala/fokot/docker/scala/service/CatRepositorySlickTest.scala
I would do a PR but i don't know where (to which package) as I couldn't even find HasMysqlDatabase. So tell me and I can contribute :)
from docker-it-scala.
Cool, thanks. Could you please adding ability to pass port (but keep default).
Otherwise this code can easily fail on multiple port mapping:
container.getPorts().map(x => x.values.head)
Make a PR to samples
module please. You can put ReadyChecked into that file
https://github.com/whisklabs/docker-it-scala/blob/master/samples/src/main/scala/com/whisk/docker/DockerPostgresService.scala
from docker-it-scala.
I needed to expose port because otherwise java couldn't access postgres other than in another container with link...
from docker-it-scala.
from docker-it-scala.
Related Issues (20)
- Concurrency issues on logs
- No support for UDP?
- Timeout or Race condition resulting in Cannot run all required containers HOT 1
- Shutdown connection before running tests HOT 1
- Pulling image timeout gives an error message about not being able to pull windows image
- Publish v0.9.7 for 2.11 ? HOT 1
- Plans to publish a jar with shaded spotify docker-client? HOT 8
- Setup steps unclear HOT 2
- PostgresServiceSpec fails with driver libraries from 42 HOT 1
- Allow pausing/unpausing of containers in DockerExecutor
- Release for Scala 2.13 HOT 5
- run unpublished docker image with whisk labs docker-it-scala HOT 1
- Incompatible with ScalaTest's AsyncTestSuite
- Issues with SBT 1.3.x
- An image without a tag pulls all tags
- Persisting container across multiple test classes
- withUnlinkedDependencies not starting dependent container
- DockerContainer should have an option to configure withIpv6Address and withExtraHosts
- Missing release for docker-testkit-impl-docker-java 0.11.0 HOT 5
- Update in the GitHub Actions image's docker breaks docker-it-scala HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from docker-it-scala.