Skip to content

Instantly share code, notes, and snippets.

Created October 4, 2017 14:13
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Clojure.spec URL and email specs with generators
(require '[cemerick.url :as url]
'[clojure.spec.alpha :as s]
'[clojure.spec.gen.alpha :as gen]
'[clojure.string :as string])
(def non-empty-string-alphanumeric
"Generator for non-empty alphanumeric strings"
(gen/such-that #(not= "" %)
(def non-empty-url-encoded-string
"Generator for url-encoded strings"
(gen/such-that #(not= "" %)
(def email-gen
"Generator for email addresses"
(fn [[name host tld]]
(str name "@" host "." tld))
(def url-path-gen
"Generator that creates a string made up of one or more forward slash-separated non-empty strings"
(gen/fmap #(->> %
(map url/url-encode)
(interleave (repeat "/"))
(apply str))
(gen/such-that #(not= [] %)
(gen/such-that #(not= "" %)
(def url-gen
"Generator for generating URLs; note that it may generate http URLs on port 443 and https URLs on port 80,
and that usernames and passwords only use alphanumerics"
(gen/fmap (partial apply (comp str url/->URL))
;; protocol
(gen/elements #{"http" "https"})
;; username
;; password
;; host
;; port
(gen/choose 1 65535)
;; path
;; query
{:max-elements 10})
;; anchor
(gen/fmap url/url-encode (gen/string)))))
(s/def ::email
#(re-matches #".+@.+\..+" %)
(fn [] email-gen)))
(s/def ::url
#(try (url/url %) (catch Throwable t false))
(fn [] url-gen)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment