Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. (ns spec-ex.core
  2. (:require
  3. [clojure.spec.alpha :as s]
  4. [clojure.spec.gen.alpha :as gen]
  5. [clojure.spec.test.alpha :as stest]))
  6.  
  7. ;; [org.clojure/spec.alpha "0.1.123"]
  8.  
  9. ;; The goal is to stub functions which require some kind external
  10. ;; dependency, such as a service or other I/O.
  11.  
  12. (defprotocol Y
  13. (-do-y [r]))
  14.  
  15. (def y? (partial satisfies? Y))
  16. (s/def ::y y?)
  17.  
  18. ;; Protocol methods can't be spec'd, so wrap them in a function.
  19.  
  20. (defn do-y [r]
  21. (-do-y r))
  22.  
  23. (s/fdef do-y :args (s/cat :y-er ::y))
  24.  
  25. ;; Example of the protocol implementation that we're going to stub.
  26.  
  27. (defrecord BadYer []
  28. Y
  29. (-do-y [_] (throw (Exception. "can't make me!"))))
  30.  
  31.  
  32. ;; Confirm BadYer instances are valid with respect to the protol spec.
  33.  
  34. (s/valid? ::y (->BadYer))
  35. ;; => true
  36.  
  37. ;; And confirm BadYer instances will throw when called.
  38.  
  39. (try
  40. (do-y (->BadYer))
  41. (catch Exception e
  42. (.getMessage e)))
  43. ;; => "can't make me!"
  44.  
  45.  
  46. (def y-gen (gen/return (->BadYer)))
  47.  
  48. ;; Confirm generator works as expected:
  49.  
  50. (gen/sample y-gen 1)
  51. ;; => (#spec_ex.core.BadYer{})
  52.  
  53. ;; We want to stub `do-y`, providing y-gen as a generator for `::y`
  54.  
  55. (try
  56. (stest/instrument `do-y {:stub #{`do-y}
  57. :gen {::y (constantly y-gen)}})
  58. (catch Exception e
  59. (ex-data e)))
  60. ;; => #:clojure.spec.alpha{:path [:y-er], :form :spec-ex.core/y, :failure :no-gen}
  61.  
  62. ;; However, we *can* stub `do-y` if we replace its spec.
  63.  
  64. (stest/instrument `do-y
  65. {:stub #{`do-y}
  66. :spec {`do-y (s/fspec
  67. :args (s/cat :y-er (s/with-gen ::y
  68. (constantly y-gen))))}})
  69. ;; => [spec-ex.core/do-y]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement