Skip to content

Instantly share code, notes, and snippets.

@ztellman
Last active August 29, 2015 14:21
Show Gist options
  • Select an option

  • Save ztellman/a8812c558ce8a4cc54f1 to your computer and use it in GitHub Desktop.

Select an option

Save ztellman/a8812c558ce8a4cc54f1 to your computer and use it in GitHub Desktop.
(ns aleph.websocket-test
(:use
[clojure test])
(:require
[manifold.deferred :as d]
[manifold.stream :as s]
[aleph.netty :as netty]
[byte-streams :as bs]
[aleph.http :as http]))
(defmacro with-server [server & body]
`(let [server# ~server]
(try
~@body
(finally
(.close ^java.io.Closeable server#)))))
(defmacro with-handler [handler & body]
`(with-server (http/start-server ~handler {:port 8080})
~@body))
(defmacro with-raw-handler [handler & body]
`(with-server (http/start-server ~handler {:port 8080, :raw-stream? true})
~@body))
(defmacro with-both-handlers [handler & body]
`(do
(with-handler ~handler ~@body)
(with-raw-handler ~handler ~@body)))
(defn echo-handler [req]
(-> (http/websocket-connection req)
(d/chain #(do (s/on-closed % (fn [] (prn "closed!"))) (s/on-drained % (fn [] (prn "drained!"))) (s/connect % %)))
(d/catch (fn [_] {}))))
(deftest test-echo-handler
(with-handler echo-handler
(let [c @(http/websocket-client "ws://localhost:8080")]
(s/put! c "hello")
(is (= "hello" @(s/take! c)))
(s/close! c)
(is (= nil @(s/take! c))))
(is (= 400 (:status @(http/get "http://localhost:8080" {:throw-exceptions false}))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment