/
fixtures.clj
254 lines (221 loc) · 8.62 KB
/
fixtures.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
(ns jackdaw.test.fixtures
""
(:require
[aleph.http :as http]
[clojure.java.io :as io]
[clojure.tools.logging :as log]
[jackdaw.streams :as k]
[jackdaw.streams.interop :refer [streams-builder]]
[jackdaw.test.transports.kafka :as kt]
[jackdaw.test.serde :refer [byte-array-serializer byte-array-deserializer]]
[manifold.deferred :as d]
[clojure.test :as t])
(:import
(org.apache.kafka.clients.admin AdminClient NewTopic)
(org.apache.kafka.streams KafkaStreams$StateListener KafkaStreams$State)
(kafka.tools StreamsResetter)))
;;; topic-fixture ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- new-topic
[t]
(doto (NewTopic. (:topic-name t)
(:partition-count t)
(:replication-factor t))
(.configs (:config t))))
(defn list-topics
[client]
(.listTopics client))
(defn- create-topics
"Creates "
[client kafka-config topic-config]
(let [required (->> topic-config
(filter (fn [[k v]]
(not (.contains (-> (list-topics client)
.names
.get)
(:topic-name v)))))
(map (fn [[k v]]
(new-topic v))))]
(-> (.createTopics client required)
(.all))))
(defn- delete-topics
[client kafka-config topic-config]
(let [deletable (->> topic-config
(filter (fn [[k v]]
(.contains (-> (list-topics client)
.names
.get)
(:topic-name v))))
(map (fn [[k v]]
(:topic-name v))))]
(-> (.deleteTopics client deletable)
(.all))))
(defn topic-fixture
"Returns a fixture function that creates all the topics named in the supplied
topic config before running a test function."
([kafka-config topic-config]
(topic-fixture kafka-config topic-config 10000))
([kafka-config topic-config timeout-ms]
(fn [t]
(with-open [client (AdminClient/create kafka-config)]
(-> (create-topics client kafka-config topic-config)
(.get timeout-ms java.util.concurrent.TimeUnit/MILLISECONDS))
(log/info "topic-fixture: created topics: " (keys topic-config))
(t)))))
;;; skip-to-end ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- class-name
[instance]
(-> (.getClass instance)
(.getName)))
(defn skip-to-end
"Returns a fixture that skips to the end of the supplied topic before running
the test function"
[{:keys [topic config]}]
(fn [t]
(let [config (assoc config
"key.serializer" (class-name byte-array-serializer)
"key.deserializer" (class-name byte-array-deserializer)
"value.serializer" (class-name byte-array-serializer)
"value.deserializer" (class-name byte-array-deserializer))]
(doto (kt/subscription config [topic])
(.commitSync)
(.close))
(log/infof "skipped to end: %s" (:topic-name topic))
(t))))
;;; kstream-fixture ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- set-started
[app-id started?]
(reify KafkaStreams$StateListener
(onChange [_ new-state old-state]
(log/infof "process %s changed state from %s -> %s"
app-id
(.name old-state)
(.name new-state))
(when-not (realized? started?)
(when (= KafkaStreams$State/RUNNING new-state)
(deliver started? true))))))
(defn- set-error
[error]
(reify Thread$UncaughtExceptionHandler
(uncaughtException [_ t e]
(log/error e (.getMessage e))
(reset! error e))))
(defn kstream-fixture
"Returns a fixture that builds and starts kafka streams for the supplied topology
before running the test function (and then tears it down when the test is
complete).
`compose-fixtures` or `join-fixtures` may be used to build fixtures combine
topologies"
[{:keys [topology config]}]
(fn [t]
(let [builder (k/streams-builder)
stream (k/kafka-streams (topology builder) config)
error (atom nil)
started? (promise)]
(.setUncaughtExceptionHandler stream (set-error error))
(.setStateListener stream (set-started (get config "application.id") started?))
(k/start stream)
(when @started?
(log/info "commencing test function"))
(try
(t)
(finally
(k/close stream)
(log/infof "closed stream: %s" (get config "application.id"))
(when @error
(log/error @error (.getMessage @error))
(throw (ex-info (str "Uncaught exception: " (.getMessage @error))
{:config config
:stream stream}
@error))))))))
;; system readyness
(defn service-ready?
[{:keys [http-url http-params timeout]}]
(fn [t]
(let [ok? (fn [x]
(and (not (= :timeout x))
(= 200 (:status x))))
ready-check @(d/timeout!
(d/future
(loop []
(if-let [result (try
@(http/get http-url http-params)
(catch java.net.ConnectException _))]
result
(recur))))
timeout
:timeout)]
(if (ok? ready-check)
(t)
(throw (ex-info (format "service %s not available after waiting for %s"
http-url
timeout)
{}))))))
(defn delete-recursively [fname]
(let [func (fn [func f]
(when (.isDirectory f)
(doseq [f2 (.listFiles f)]
(func func f2)))
(clojure.java.io/delete-file f))]
(func func (clojure.java.io/file fname))))
(defn empty-state-fixture [app-config]
(fn [t]
(let [state-dir (format "%s/%s"
(or (get app-config "state.dir")
"/tmp/kafka-streams")
(get app-config "application.id"))]
(when (.exists (io/file state-dir))
(log/info "deleting state dir: " state-dir)
(delete-recursively state-dir))
(t))))
;;; reset-application-fixture ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn default-reset-fn
[rt args]
(.run rt (into-array String args)))
(defn reset-application-fixture
"Returns a fixture that runs the kafka.tools.StreamsResetter with the supplied
`reset-args` as parameters"
([app-config]
(reset-application-fixture app-config [] default-reset-fn))
([app-config reset-args]
(reset-application-fixture app-config reset-args default-reset-fn))
([app-config reset-args reset-fn]
(fn [t]
(let [rt (StreamsResetter.)
app-id (get app-config "application.id")
args (concat ["--application-id" (get app-config "application.id")
"--bootstrap-servers" (get app-config "bootstrap.servers")]
reset-args)
result (with-open [out-str (java.io.StringWriter.)
err-str (java.io.StringWriter.)]
(binding [*out* out-str
*err* err-str]
(let [status (reset-fn rt args)]
(flush)
{:status status
:out (str out-str)
:err (str err-str)})))]
(if (zero? (:status result))
(t)
(throw (ex-info "failed to reset application. check logs for details"
result)))))))
(defn integration-fixture
[build-fn {:keys [broker-config
topic-metadata
app-config
enable?]}]
(t/join-fixtures
(if enable?
(do
(log/info "enabled intregration fixtures")
[(topic-fixture broker-config topic-metadata)
(reset-application-fixture app-config)
(kstream-fixture {:topology (build-fn topic-metadata)
:config app-config})])
(do
(log/info "disabled integration fixtures")
[(empty-state-fixture app-config)]))))
(defmacro with-fixtures
[fixtures & body]
`((t/join-fixtures ~fixtures)
(fn []
~@body)))