How to check distinct id in spec/coll-of
Asked Answered
E

1

5
(s/def ::users (s/coll-of ::user :distinct true))

The spec above requires each user map to be distinct but How can I specify it to check for distinct :user/ids only

The collection bellow shouldn't be allowed:

[{:id 10 :name "Jessica"} {:id 10 :name "Erica"}]
Entirety answered 9/9, 2017 at 21:6 Comment(1)
Can you give more context? Are you trying to generate sample data? Or, are you trying to test a function? Could you just use a single map with ID as key and NAME as value? Could you generate unique IDs first, then associate random (possibly non-unique) names to each ID?Wamble
C
8
(s/def ::id (s/int-in 0 40)) ; just for testing purposes
(s/def ::name string?)
(s/def ::user (s/and (s/keys :req-un [::id ::name])))
(s/def ::user-list (s/and
                       (s/coll-of ::user :distinct true :into [])
                       #(if (empty? %) true (apply distinct? (mapv :id %)))))

(deftest so-test
    (let [users [{:id 11 :name "Jessica"} {:id 11 :name "Erica"}]]
        (prn (g/generate (s/gen ::user-list)))
        (s/assert ::user-list users)))
Colston answered 10/9, 2017 at 1:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.