Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature inquiry: a convenience function for validating a value against a spec #214

Closed
aviflax opened this issue Feb 11, 2021 · 4 comments
Closed

Comments

@aviflax
Copy link

aviflax commented Feb 11, 2021

I feel like I’ve written variations on this fn across a bunch of projects:

(defn valid?!
  [spec val error-prefix]
  (when-not (s/valid? spec val)
    (throw (ex-info (str error-prefix ": " (expound/expound-str spec val {:print-specs? false}))
                    (s/explain-data spec val)))))

so I’m wondering whether this, or something similar, might be a good idea to include in Expound?

I’d be happy to submit a PR, if so.

Thank you!

@bhb
Copy link
Owner

bhb commented Feb 11, 2021

@aviflax Thanks for the idea, I appreciate it!

At least for now, I'm going to keep Expound focused on just improving the spec error messages. This is method is useful, but I think it's a better fit for a separate library.

@bhb bhb closed this as completed Feb 11, 2021
@aviflax
Copy link
Author

aviflax commented Feb 11, 2021 via email

@devurandom
Copy link

For reference, in case someone finds it useful, here is a clojure.test helper I wrote to make the "diff" of spec validations readable without having to litter my test code with (is (= "Success!\n" (expound/expound-str :my/spec x))):

(require [clojure.test :refer :all])
(require [expound.alpha :as expound])
(require [clojure.spec.alpha :as s])

(defmethod assert-expr 'valid?
  [message [_ spec actual]]
  `(do-report
     {:type     (if (s/valid? ~spec ~actual) :pass :fail)
      :message  ~message
      :expected "Success!\n"
      :actual   (expound/expound-str ~spec ~actual)}))

(declare handler)

(deftest example-test
  (testing "that response is valid"
    (let [{:keys [body]} (handler {:body-params {:sample "input"}})]
      (is (valid? :my/spec body)))))

At least in Cursive / IntelliJ this displays well.

@bhb
Copy link
Owner

bhb commented Sep 30, 2022

@devurandom Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants