请分享您的想法,参加2024年Clojure状态调查!

欢迎!请查看关于页面了解如何使用本站的相关信息。

0
规格

有关如何验证可选键的问题在Slack上讨论。我本来打算指给他们看`s/keys`的文档字符串,但觉着其可能需要一些澄清。下面是相关的文档字符串

-------------------------
clojure.spec.alpha/keys
([& {:keys [req req-un opt opt-un gen]}])
Macro
  Creates and returns a map validating spec. :req and :opt are both
  vectors of namespaced-qualified keywords. The validator will ensure
  the :req keys are present. The :opt keys serve as documentation and
  may be used by the generator.

  The :req key vector supports 'and' and 'or' for key groups:

  (s/keys :req [::x ::y (or ::secret (and ::user ::pwd))] :opt [::z])

  There are also -un versions of :req and :opt. These allow
  you to connect unqualified keys to specs.  In each case, fully
  qualfied keywords are passed, which name the specs, but unqualified
  keys (with the same name component) are expected and checked at
  conform-time, and generated during gen:

  (s/keys :req-un [:my.ns/x :my.ns/y])

  The above says keys :x and :y are required, and will be validated
  and generated by specs (if they exist) named :my.ns/x :my.ns/y 
  respectively.

  In addition, the values of *all* namespace-qualified keys will be validated
  (and possibly destructured) by any registered specs. Note: there is
  no support for inline value specification, by design.

  Optionally takes :gen generator-fn, which must be a fn of no args that
  returns a test.check generator.

我期望看到:如果由`:opt`或`:opt-un`指定的键存在,它们将与相应键的规格进行比较验证。然而,它仅提到这只是一个说明。

这似乎可能需要一些澄清。

1 答案

+1

被选中
 
最佳答案

此外,所有命名空间合格键的值将由注册的任何规格进行验证(并可能被解构)。

我读过它,感觉有点微妙。这也让我想到,以下这种情况可能是错误的,因为`::c`是一个已注册的、命名空间的规范。

(s/def ::c pos-int?)
(s/valid? (s/keys :opt-un []) {:c "3"})

我唯一能解释这一点的方式是,如果有可选键出现,那么只有所有命名空间合格键都经过验证后,才会对这些可选键进行验证。
我认为,我在那里思考得有点简单,但我相信这确实涵盖了这一点。我被“命名空间合格键”这词的歧义弄糊涂了,它指的是在req、req-un、opt和opt-un向量的键,而不是地图中的键。无论如何,感谢您在这么晚的时候给了我答案。
...