Skip to content

Instantly share code, notes, and snippets.

@DanThiffault
Created January 16, 2017 02:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanThiffault/89e08d0c508852ef234b37c0326b90fe to your computer and use it in GitHub Desktop.
Save DanThiffault/89e08d0c508852ef234b37c0326b90fe to your computer and use it in GitHub Desktop.
Clojure Spec examples
(ns spec-examples
(:require
[clojure.spec :as s]
[clojure.spec.gen :as gen]
[clojure.future :refer :all]))
;; Define a map called user-info of { :region-id :region :template-id :template }
;; and ensure that the generated regions contain the passed in region-id (same for templates)
(s/def ::region-id (s/and nat-int? #(> % 1000)))
(s/def ::regions (s/map-of ::region-id string? :min-count 1))
(s/def ::template-id (s/and string? #(> (count %) 2)))
(s/def ::templates (s/map-of ::template-id string? :min-count 1))
(defn user-info-gen
[]
(gen/bind
(gen/tuple (s/gen ::regions) (s/gen ::templates))
(fn [[regions templates]]
(gen/hash-map
::regions (gen/return regions)
::region-id (gen/elements (keys regions))
::templates (gen/return templates)
::template-id (gen/elements (keys templates))))))
(defn ensure-valid-lookup
[map-kw key-kw]
(fn [obj]
(contains? (get obj map-kw) (get obj key-kw))))
(s/def ::user-info (s/with-gen
(s/and (s/keys :req [::regions ::region-id
::templates ::template-id])
(ensure-valid-lookup ::regions ::region-id)
(ensure-valid-lookup ::templates ::template-id))
user-info-gen))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment