-
Notifications
You must be signed in to change notification settings - Fork 0
/
matching.cljc
91 lines (72 loc) · 1.9 KB
/
matching.cljc
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
(ns dgknght.app-lib.web-mocks.matching
(:require [dgknght.app-lib.core :as lib])
#?(:clj (:import java.util.regex.Pattern)))
#?(:clj
(defn- regexp?
[v]
(instance? Pattern v)))
(defn- dispatch-matcher
[matcher]
(cond
(regexp? matcher) :pattern
(string? matcher) :string
(map? matcher) :map
(keyword? matcher) :keyword
(ifn? matcher) :fn))
(defmulti match-value?
(fn [_ matcher]
(dispatch-matcher matcher)))
(defmethod match-value? :default
[value matcher]
(= value matcher))
(defmethod match-value? :pattern
[value matcher]
(re-find matcher value))
(defmethod match-value? :fn
[value matcher]
(matcher value))
(defmulti match? (fn [_req matcher]
(dispatch-matcher matcher)))
(defmethod match? :string
[{:keys [url]} matcher]
(= url matcher))
(defmethod match? :pattern
[req pattern]
(re-find pattern (:url req)))
(defmethod match? :map
[req matcher]
(->> matcher
(map (fn [[k v]]
(match-value? (get-in req [k])
v)))
(every? identity)))
(defmethod match? :fn
[req f]
(f req))
(defmulti meets-spec?
(fn [_match-count spec]
(cond
(keyword? spec) ::keyword
(map? spec) ::map)))
(defmethod meets-spec? ::map
[match-count {:keys [times]}]
(= times match-count))
(defmethod meets-spec? ::keyword
[match-count spec]
(case spec
:once (= 1 match-count)
:twice (= 2 match-count)
(throw (ex-info (lib/format "Unrecognized call spec %s" spec) {:spec spec}))) )
(defmulti readable dispatch-matcher)
(defmethod readable :pattern
[matcher]
(str "request with url matching \"" matcher "\""))
(defmethod readable :string
[matcher]
(str "request with url \"" matcher "\""))
(defmethod readable :map
[matcher]
(str "request with attributes " (prn-str matcher)))
(defmethod readable :fn
[_matcher]
"request matching predicate fn")