Skip to content

Instantly share code, notes, and snippets.

@mattmoss
Created November 13, 2012 21:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmoss/4068423 to your computer and use it in GitHub Desktop.
Save mattmoss/4068423 to your computer and use it in GitHub Desktop.
Using conch to start/stop a server in a clojure.test fixture
(ns test.connection
(:require [clojure.test :refer :all]
[conch.core :as conch]
[conch.sh :as sh]))
(def ^:private process-name "./server.sh")
(def ^:private process-dir "/Users/mattmoss/samples/")
(def ^:private patt-server-url #"Server bound to (http://localhost:\d+)")
(def ^:dynamic *server-url* nil)
(defn- read-until [s re]
(loop [x (first s) xs (rest s)]
(when x
(if-let [m (re-find re x)]
[m xs]
(recur (first xs) (rest xs))))))
(defn- start-server []
"Starts the sample server. Waits for the simulation to start, then returns the server URL and the process map."
(sh/let-programs [my-server (str process-dir process-name)]
(let [p (my-server :dir process-dir {:verbose true :seq true})
[url out] (read-until (:stdout p) patt-server-url)
url (nth url 1)]
(read-until out #"Server started")
[url p])))
(defn- stop-server [p]
"Sends stop command to the sample server. Waits for the simulation to stop."
(conch/feed-from-string (:proc p) "x\n") ; this tells the server to shutdown cleanly
(read-until (:stdout p) #"Server closed")
nil)
(defn with-server [f]
"A clojure.test fixture to start the sample server before tests and stop the server after."
(let [[url p] (start-server)]
(binding [*server-url* url]
(try
(f)
(finally (stop-server p))))))
(use-fixtures :once with-server)
(deftest t-foo
(is (= 0 1)))
;; TODO more tests go here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment