Skip to content

Instantly share code, notes, and snippets.

@jsofra
Created August 25, 2020 02:31
Show Gist options
  • Save jsofra/1c49b4af2b3b4f99eb67762dcd1cf623 to your computer and use it in GitHub Desktop.
Save jsofra/1c49b4af2b3b4f99eb67762dcd1cf623 to your computer and use it in GitHub Desktop.
Demonstrating using testcontainers.org library from Clojure
(ns db-fixture
(:require [config :as config])
(:import (org.testcontainers.containers GenericContainer
BindMode)))
(defn create-db-container [{:keys [dbname user password]}]
(-> (GenericContainer. "postgres:12.2")
(.withExposedPorts (into-array Integer [(int 5432)]))
(.withEnv "POSTGRES_DB" dbname)
(.withEnv "POSTGRES_USER" user)
(.withEnv "POSTGRES_PASSWORD" password)
(.withClasspathResourceMapping "schema.sql"
"/opt/schema.sql"
BindMode/READ_ONLY)))
(defn load-schema [container {:keys [dbname user]}]
(.execInContainer container (into-array ["psql" "-U" user "-f" "/opt/schema.sql" dbname])))
(def test-db-container (create-db-container (:db-spec config/app-config)))
(defn test-db-networking []
(when (.isRunning test-db-container)
{:port (.getFirstMappedPort test-db-container)
:host (.getHost test-db-container)}))
(defn setup
"Setup and start a db container."
[]
(when (not (.isRunning test-db-container))
(doto test-db-container
(.start)
(load-schema (:db-spec config/app-config)))))
(defn tear-down
"Stop the running db container."
[]
(.stop test-db-container))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment