Fork me on GitHub
#clojure-spec
<
2019-01-12
>
blance00:01:21

Is it idiomatic to use spec to validate data with remote service through http request?

seancorfield00:01:22

@blance I think it's idiomatic to use spec for validating data in a lot of cases. Can you be a bit more specific?

seancorfield00:01:46

For example, we use to spec to validate (and conform) input arguments to our REST APIs and in some other places either before or after interaction with an external system.

blance00:01:34

say I have a user id that needs to be an int, normally i would just validate it using int?. i'm just curious does it make sense to also do

(def ::user (s/and int? user-exist?)) 

blance00:01:55

where user-exist would have to call to an external service to check if user exists

seancorfield00:01:28

I'd be careful about using predicates that rely on outside systems for your specs. That feels wrong to me.

5
lilactown00:01:33

if you try and use ::user with generators, are you going to be upset if it sends hundreds of thousands of requests to your external service?

seancorfield00:01:09

Yup. I would say it's worth trying to stick with specs that can be used in generators.

lilactown00:01:35

sometimes it's surprising which spec functions use generators too. e.g. instrumentation

blance00:01:00

i haven't really start looking at generative testing yet

blance00:01:31

i suppose http request can be mocked during testing?

blance00:01:02

reading more on the doc,

A key design constraint of spec is that all specs are also designed to act as generators of sample data that conforms to the spec
sounds like I shouldn't be using any non trivial pred that can't easily generate good sample data

misha12:01:07

You can use non-trivial predicates (and, I think, it is one of the value props of spec), but if you end up using it for generative testing you will have to help that predicate with a custom generator to minimize "Couldn't satisfy such-that predicate after 100 tries" errors (https://clojure.org/guides/spec#_custom_generators) You can write predicates with side-effects, but as with usual code – try to isolate them from the pure ones, and know all the contexts where those might be used. So checking if user exists is perfectly fine, but probably should be done at a very specific points of the system, separate from checking hypothetical user's structure. Also: "not everything needs to be a spec", as well as "not everything needs to be specced". @blance

blance23:01:45

that make perfect sense, thanks!

trevor20:01:30

I'm struggling on how to create a generator that returns a constant value

trevor20:01:43

my example is UUID or constant id

trevor20:01:32

(gen/one-of [(s/gen ::uuid) ...])

trevor20:01:47

let's say the constant is 0

trevor20:01:46

I was looking for gen/return