Files
tbd/test/tbd/core_test.clj
ajet 5aaf5a8d6c
CI / Test + coverage (push) Successful in 59s
add webmcp
2026-09-19 13:38:27 -09:00

71 lines
3.0 KiB
Clojure

(ns tbd.core-test
(:require [clojure.test :refer [deftest is testing]]
[ring.middleware.defaults :refer [wrap-defaults api-defaults]]
[tbd.core :as core])
(:import (java.io ByteArrayOutputStream PrintStream)
(java.net ServerSocket)))
;; Same middleware stack start-server wraps around the app.
(def handler (wrap-defaults core/app api-defaults))
(defn request [method uri]
(handler {:request-method method :uri uri :headers {}}))
(deftest root-test
(let [resp (request :get "/")
body (slurp (:body resp))]
(is (= 200 (:status resp)))
(is (= "text/html; charset=utf-8" (get-in resp [:headers "Content-Type"])))
(testing "serves the HTML shell that mounts the re-frame UI"
(is (re-find #"<div id=\"app\"" body))
(is (re-find #"<script src=\"/js/main\.js\"" body))))
(testing "HEAD is served like GET, without a body"
(is (= 200 (:status (request :head "/"))))))
(deftest origin-trial-header-test
(let [get-root (fn [config]
((core/make-app config) {:request-method :get :uri "/" :headers {}}))]
(testing "the WebMCP origin-trial token is sent as an Origin-Trial header on the page"
(is (= "tok-123" (get-in (get-root (assoc core/config :webmcp {:origin-trial-token "tok-123"}))
[:headers "Origin-Trial"]))))
(testing "no token, no header"
(is (nil? (get-in (get-root (assoc core/config :webmcp {:origin-trial-token nil}))
[:headers "Origin-Trial"]))))))
(deftest js-assets-test
;; main.js only exists once script/ui-build has run, so only the miss is asserted here;
;; the integration suite (which runs against the built image) checks the hit.
(is (= 404 (:status (request :get "/js/nope.js")))))
(deftest swagger-spec-test
(let [resp (request :get "/swagger.json")]
(is (= 200 (:status resp)))
(is (re-find #"/api/ping" (slurp (:body resp))))
(is (not (re-find #"\"definitions\":null" (slurp (:body (request :get "/swagger.json")))))
"a null `definitions` makes the spec invalid Swagger 2.0")))
(deftest unknown-route-test
(is (= 404 (:status (request :get "/nope")))))
(defmacro with-err-silenced
"start-server prints the stack trace via System/err, which with-out-str doesn't capture."
[& body]
`(let [orig# System/err]
(System/setErr (PrintStream. (ByteArrayOutputStream.)))
(try ~@body (finally (System/setErr orig#)))))
(deftest start-server-failure-test
(testing "a port that is already taken is reported and rethrown"
(let [env-port (System/getenv "PORT")]
(with-open [taken (ServerSocket. (if env-port (parse-long env-port) 0))]
(is (thrown? Throwable
(with-err-silenced
(with-out-str
(core/start-server nil {:port (.getLocalPort taken)})))))))))
(deftest main-test
(let [calls (atom 0)]
(with-redefs [core/start-server (fn [& _] (swap! calls inc))]
(core/-main))
(is (= 1 @calls))))