如何检查Clojure规范的可解析性?

时间:2017-08-22 13:42:42

标签: clojure clojure.spec

clojure.spec.alpha允许用户在定义新规范时使用不可解析的规范:

(s/def :foo/bar (s/or :nope :foo/foo))

此处:foo/foo无法解析,因此使用:foo/bar会引发使用异常:

(s/valid? :foo/bar 42)
;; Exception Unable to resolve spec: :foo/foo  clojure.spec.alpha/reg-resolve! (alpha.clj:69)

当我使用:my-ns/my-spec而不是::my-ns/my-spec进行拼写错误时,我的代码就会发生这种情况。我想抓住单元测试的那些。

Firebase Notifications中潜水我发现我可以使用(keys (s/registry))获取所有规格,所以我的测试看起来像这样:

(ns my-ns.spec-test
  (:require [clojure.test :refer :all]
            [clojure.spec.alpha :as s]
            ;; :require all the relevant namespaces to populate the
            ;; global spec registry.
            [my-ns.spec1]
            [my-ns.spec2]))

(deftest resolvable-specs
  (doseq [spec (keys (s/registry))]
    (is (resolvable? spec))))
    ;;   ^^^^^^^^^^^ placeholder; that’s the function I want

不幸的是s/resolvable?中没有clojure.spec.alpha这样的东西。到目前为止,我发现的唯一解决方案是调用(s/valid? spec 42)并假设它没有引发异常意味着它可以解析,但它不会检查所有分支:

(s/def :int/int int?)
(s/def :bool/bool bool?)

(s/def :my/spec (s/or :int :int/int
                      :other (s/or :bool bool/bool
                                   :nope :idont/exist)))

(s/valid? :my/spec 1) ; <- matches the :int branch
;; => true

(s/valid? :my/spec :foo)
;; Exception Unable to resolve spec: :idont/exist  clojure.spec.alpha/reg-resolve! (alpha.clj:69)

我检查了异常堆栈跟踪以及源代码,看看我是否可以找到任何函数来完全解析规范,而不使用上面的42:foo这样的测试值但是找不到任何

有没有办法检查,对于给定的规范,它在所有分支中引用的所有规范是否都存在?

1 个答案:

答案 0 :(得分:1)

我能够做到以下几点:

(ns my-ns.utils
  (:require [clojure.spec.alpha :as s]))

(defn- unresolvable-spec
  [spec]
  (try
    (do (s/describe spec) nil)
    (catch Exception e
      (if-let [[_ ns* name*] (re-matches #"Unable to resolve spec: :([^/]+)/(.+)$" (.getMessage e))]
        (keyword ns* name*)
        (throw e)))))

(defn unresolvable?
  "Test if a spec is unresolvable, and if so return a sequence
   of the unresolvable specs it refers to."
  [spec]
  (cond
    (symbol? spec)
      nil

    (keyword? spec)
      (if-let [unresolvable (unresolvable-spec spec)]
        [unresolvable]
        (not-empty (distinct (unresolvable? (s/describe spec)))))

    (seq? spec)
      (case (first spec)
        or (->> spec (take-nth 2) rest (mapcat unresolvable?))
        and (->> spec rest (mapcat unresolvable?))

        ;; undecidable
        nil)

    :default (unresolvable-spec spec)))

(def resolvable? (complement unresolvable?))

适用于s/ands/or,这是我的最小用例:

(u/resolvable? :int/int) ;; => true
(u/resolvable? :my/spec) ;; => false
(u/unresolvable? :my/spec) ;; => (:idont/exist)

但它有一些缺陷:

  • 重新发明轮子;我认为那些规范行走函数已经存在于clojure.spec.alpha
  • 中的某个地方
  • 它依赖于捕获异常然后解析它的消息,因为(1)clojure.spec.alpha没有不引发异常的函数和(2)引发异常的函数不使用任何东西比Exception
  • 更具体

如果某人有更健壮的话,我会很乐意接受任何其他答案。