/
test.clj
229 lines (198 loc) · 8.57 KB
/
test.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
(ns clj-chrome-devtools.cljs.test
"Build a ClojureScript build and run its tests as a clojure
test. This can hook your cljs app tests into the normal
clojure testing run."
(:require [cljs.build.api :as cljs-build]
[clojure.java.io :as io]
[clj-chrome-devtools.automation.fixture :refer [create-chrome-fixture]]
[clj-chrome-devtools.automation :as automation]
[clj-chrome-devtools.impl.util :refer [random-free-port]]
[org.httpkit.server :as http-server]
[clojure.string :as str]
[clojure.test]
[clojure.java.shell :as sh])
(:import (java.io File)))
(defn no-op-log [& args]
nil)
(defn println-log [& args]
(println (str/join " " args)))
(def ^:dynamic log no-op-log)
(defn- find-defproject [file]
(log "Loading leiningen project from: " file)
(with-open [in (java.io.PushbackReader. (io/reader file))]
(loop [form (read in false ::eof)]
(cond
(= ::eof form)
(throw (ex-info "Can't find defproject form" {:file file}))
(and (coll? form) (= (first form) 'defproject))
(do
(log "Found defproject: " (nth form 1) (nth form 2))
form)
:else
(recur (read in))))))
(defn- load-project-clj
"Load project.clj file and turn it into a map."
[]
(->> "project.clj" find-defproject
(drop 3) ;; remove defproject, name and version
(partition 2) ;; take top level :key val pairs
(map vec)
(into {})))
(defn- build-by-id [project-clj build-id]
(->> project-clj :cljsbuild :builds
(some #(when (= build-id (:id %))
%))))
(defn- test-runner-forms
"ClojureScript forms for test runner"
[namespaces]
(log "Generating test runner forms for namespaces: " namespaces)
(-> "clj_chrome_devtools_runner.tpl"
io/resource slurp
(str/replace "__REQUIRE_NAMESPACES__"
(str/join "\n " namespaces))
(str/replace "__TEST_NAMESPACES__"
(str/join "\n "
(map #(str "'" %) namespaces)))))
(defn- with-test-runner-source [namespaces source-path fun]
;; Create a test runner source file in the given source path
;; We have to put this in an existing source path as
;; we can't add a new source path dynamically (files therein
;; won't be found with io/resource). It is simpler to add
;; it to an existing source path and remove afterwards.
(let [runner (io/file source-path
"clj_chrome_devtools_runner.cljs")]
(spit runner (test-runner-forms namespaces))
(try
(fun)
(finally
(io/delete-file runner)))))
(defn build [project-clj build-id test-runner-namespaces]
(let [{:keys [source-paths compiler] :as build}
(build-by-id project-clj build-id)]
(log "Building ClojureScript, source paths: " source-paths)
(with-test-runner-source test-runner-namespaces (last source-paths)
#(cljs-build/build
(cljs-build/inputs source-paths)
(assoc compiler
:main "clj-chrome-devtools-runner"
:warnings {:single-segment-namespace false})))
(assert (.exists (io/file (:output-to compiler)))
"build output file exists")
{:js (:output-to compiler)
:js-directory (:output-dir compiler)}))
(defn- test-page [js]
(-> "test-page.tpl" io/resource slurp
(str/replace "__JS__" js)))
(defn- file-handler [{:keys [uri request-method] :as req}]
(log "REQUEST: " uri)
(let [file (io/file "." (subs uri 1))]
(if (and (= request-method :get) (.canRead file))
{:status 200
:headers {"Content-Type" (cond
(str/ends-with? uri ".html")
"text/html"
(str/ends-with? uri ".js")
"application/javascript"
:else
"application/octet-stream")}
:body (slurp file)}
{:status 404})))
(def ^{:doc "cljs.test failure/error report regex"
:private true}
final-test-report-pattern #"(\d+) failures, (\d+) errors.")
(defn- assert-test-result [msg]
(let [[match errors failures] (re-matches final-test-report-pattern msg)]
(when match
(assert (= "0" errors failures)
"ClojureScript tests had failures or errors, see previous output for details.")
true)))
(defn- poll-test-execution []
(loop [started? false
screenshots []]
(if (not started?)
;; Tests have not started yet, check for fatal error or start flag
(if-let [fatal-error (automation/evaluate "window['CLJ_FATAL_ERROR'] || null")]
(throw (ex-info "Test page had error before tests were started." {:error fatal-error}))
(if (automation/evaluate "window['CLJ_TESTS_STARTED'] || false")
(recur true screenshots)
(do
(Thread/sleep 100)
(recur false screenshots))))
;; Tests have started, poll for screenshots and printed output
(if-let [screenshot-file-name (automation/evaluate "window['CLJ_SCREENSHOT_NAME'] || null")]
(do
;; Take screenshot if requested
(log "Taking screenshot to:" screenshot-file-name)
(automation/screenshot @automation/current-automation screenshot-file-name)
(automation/evaluate "window.CLJ_SCREENSHOT_NAME = null")
(automation/evaluate "window.CLJ_SCREENSHOT_RESOLVE(true)")
(recur started? (conj screenshots screenshot-file-name)))
(let [msgs (automation/evaluate "clj_chrome_devtools_runner.get_printed()")]
(doseq [m (mapcat #(str/split % #"\n") msgs)]
(println "[CLJS]" m))
(if-not (some assert-test-result msgs)
(do
(Thread/sleep 100)
(recur started? screenshots))
screenshots))))))
(defn output-screenshot-videos [screenshots framerate]
(let [video-names (into #{}
(keep #(second (re-matches #"^([^\d]+)-(\d+)\.png$" %)))
screenshots)]
(loop [[video-name & video-names] video-names]
(when video-name
(let [input (str video-name "-%d.png")
output (str video-name ".gif")
cmd ["ffmpeg" "-framerate" "2" "-y" "-i" input output]]
(println "Generate video " output)
(let [{exit :exit err :err} (apply sh/sh cmd)]
(if (zero? exit)
(recur video-names)
(println "Failed to generate video with command: \n > "
(str/join " " cmd)
"\n Check ffmpeg installation, subprocess err: \n"
err))))))))
(defn run-tests
([build-output]
(run-tests build-output nil))
([{:keys [js js-directory]} {:keys [headless? no-sandbox? screenshot-video? framerate
ring-handler]}]
(log "Run compiled js test file:" js)
(let [chrome-fixture (create-chrome-fixture {:headless? (if (some? headless?)
headless?
true)
:no-sandbox? no-sandbox?})]
(chrome-fixture
(fn []
(log "Chrome launched")
(let [con (.-connection @automation/current-automation)
port (random-free-port)
server (http-server/run-server (fn [req]
(or (and ring-handler (ring-handler req))
(file-handler req)))
{:port port})
dir (io/file ".")
f (File/createTempFile "test" ".html" (io/file "."))
url (str "http://localhost:" port "/" (.getName f))]
(try
(spit f (test-page js))
(log "Navigate to:" url)
(automation/to url)
(log "Wait for test output")
(let [screenshots (poll-test-execution)]
(when screenshot-video?
(output-screenshot-videos screenshots (or framerate 2))))
(log "Tests done, cleanup")
(server)
(finally
(io/delete-file f)))))))))
(defn build-and-test
([build-id namespaces]
(build-and-test build-id namespaces nil))
([build-id namespaces options]
(binding [log (if (:verbose? options)
println-log
no-op-log)]
(let [project-clj (load-project-clj)
build-output (build project-clj build-id namespaces)]
(run-tests build-output options)))))