-
Notifications
You must be signed in to change notification settings - Fork 107
/
generators.cljc
1761 lines (1511 loc) · 64.5 KB
/
generators.cljc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
; Copyright (c) Rich Hickey, Reid Draper, and contributors.
; All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.test.check.generators
(:refer-clojure :exclude [abs int vector list hash-map map keyword
char boolean byte bytes sequence
shuffle not-empty symbol namespace
set sorted-set uuid double let])
(:require [#?(:clj clojure.core :cljs cljs.core) :as core
#?@(:cljs [:include-macros true])]
[clojure.string :as string]
[clojure.test.check.random :as random]
[clojure.test.check.rose-tree :as rose]
#?@(:cljs [[goog.string :as gstring]
[clojure.string]]))
#?(:cljs (:require-macros [clojure.test.check.generators :refer [let]])))
;; Gen
;; (internal functions)
;; ---------------------------------------------------------------------------
(defrecord Generator [gen])
(defn generator?
"Test if `x` is a generator. Generators should be treated as opaque values."
[x]
(instance? Generator x))
(defn- make-gen
[generator-fn]
(Generator. generator-fn))
(defn call-gen
"Internal function."
{:no-doc true}
[{generator-fn :gen} rnd size]
(generator-fn rnd size))
(defn gen-pure
"Internal function."
{:no-doc true}
[value]
(make-gen
(fn [rnd size]
value)))
(defn gen-fmap
"Internal function."
{:no-doc true}
[k {h :gen}]
(make-gen
(fn [rnd size]
(k (h rnd size)))))
(defn gen-bind
"Internal function."
{:no-doc true}
[{h :gen} k]
(make-gen
(fn [rnd size]
(core/let [[r1 r2] (random/split rnd)
inner (h r1 size)
{result :gen} (k inner)]
(result r2 size)))))
(defn lazy-random-states
"Internal function.
Given a random number generator, returns an infinite lazy sequence
of random number generators."
{:no-doc true}
[rr]
(lazy-seq
(core/let [[r1 r2] (random/split rr)]
(cons r1
(lazy-random-states r2)))))
(defn- gen-tuple
"Takes a collection of generators and returns a generator of vectors."
[gens]
(make-gen
(fn [rnd size]
(mapv #(call-gen % %2 size) gens (random/split-n rnd (count gens))))))
;; Exported generator functions
;; ---------------------------------------------------------------------------
(defn fmap
"Returns a generator like `gen` but with values transformed by `f`.
E.g.:
(gen/sample (gen/fmap str gen/nat))
=> (\"0\" \"1\" \"0\" \"1\" \"4\" \"3\" \"6\" \"6\" \"4\" \"2\")
Also see gen/let for a macro with similar functionality."
[f gen]
(assert (generator? gen) "Second arg to fmap must be a generator")
(gen-fmap #(rose/fmap f %) gen))
(defn return
"Creates a generator that always returns `value`,
and never shrinks. You can think of this as
the `constantly` of generators. E.g.:
(gen/sample (gen/return 42))
=> (42 42 42 42 42 42 42 42 42 42)"
[value]
(gen-pure (rose/pure value)))
(defn- bind-helper
[f]
(fn [rose]
(gen-fmap rose/join
(make-gen
(fn [rnd size]
(rose/fmap #(call-gen (f %) rnd size)
rose))))))
(defn bind
"Creates a new generator that passes the result of `gen` into function
`f`. `f` should return a new generator. This allows you to create new
generators that depend on the value of other generators. For example,
to create a generator of permutations which first generates a
`num-elements` and then generates a shuffling of `(range num-elements)`:
(gen/bind gen/nat
;; this function takes a value generated by
;; the generator above and returns a new generator
;; which shuffles the collection returned by `range`
(fn [num-elements]
(gen/shuffle (range num-elements))))
Also see gen/let for a macro with similar functionality."
[generator f]
(assert (generator? generator) "First arg to bind must be a generator")
(gen-bind generator (bind-helper f)))
;; Helpers
;; ---------------------------------------------------------------------------
(defn make-size-range-seq
"Internal function."
{:no-doc true}
[max-size]
(cycle (range 0 max-size)))
(defn sample-seq
"Returns an infinite sequence of realized values from `generator`.
Note that this function is a dev helper and is not meant to be used
to build other generators."
([generator] (sample-seq generator 200))
([generator max-size]
(core/let [r (random/make-random)
size-seq (make-size-range-seq max-size)]
(core/map #(rose/root (call-gen generator %1 %2))
(lazy-random-states r)
size-seq))))
(defn sample
"Return a sequence of `num-samples` (default 10)
realized values from `generator`.
The sequence starts with small values from the generator, which
probably do not reflect the variety of values that will be generated
during a longer test run.
Note that this function is a dev helper and is not meant to be used
to build other generators."
([generator]
(sample generator 10))
([generator num-samples]
(assert (generator? generator) "First arg to sample must be a generator")
(take num-samples (sample-seq generator))))
(defn generate
"Returns a single sample value from the generator.
Note that this function is a dev helper and is not meant to be used
to build other generators.
Optional args:
- size: the abstract size parameter, defaults to 30
- seed: the seed for the random number generator, an integer"
{:added "0.8.0"}
([generator]
(generate generator 30))
([generator size]
(core/let [rng (random/make-random)]
(rose/root (call-gen generator rng size))))
([generator size seed]
(core/let [rng (random/make-random seed)]
(rose/root (call-gen generator rng size)))))
;; Internal Helpers
;; ---------------------------------------------------------------------------
(defn- halfs
[n]
(take-while #(not= 0 %) (iterate #(quot % 2) n)))
(defn- shrink-int
[integer]
(core/map #(- integer %) (halfs integer)))
(defn- int-rose-tree
[value]
(rose/make-rose value (core/map int-rose-tree (shrink-int value))))
;; calc-long is factored out to support testing the surprisingly tricky double math. Note:
;; An extreme long value does not have a precision-preserving representation as a double.
;; Be careful about changing this code unless you understand what's happening in these
;; examples:
;;
;; (= (long (- Integer/MAX_VALUE (double (- Integer/MAX_VALUE 10)))) 10)
;; (= (long (- Long/MAX_VALUE (double (- Long/MAX_VALUE 10)))) 0)
(defn- calc-long
[factor lower upper]
;; these pre- and post-conditions are disabled for deployment
#_ {:pre [(float? factor) (>= factor 0.0) (< factor 1.0)
(integer? lower) (integer? upper) (<= lower upper)]
:post [(integer? %)]}
;; Use -' on width to maintain accuracy with overflow protection.
#?(:clj
(core/let [width (-' upper lower -1)]
;; Preserve long precision if the width is in the long range. Otherwise, we must accept
;; less precision because doubles don't have enough bits to preserve long equivalence at
;; extreme values.
(if (< width Long/MAX_VALUE)
(+ lower (long (Math/floor (* factor width))))
;; Clamp down to upper because double math.
(min upper (long (Math/floor (+ lower (* factor width)))))))
:cljs
(long (Math/floor (+ lower (- (* factor (+ 1.0 upper))
(* factor lower)))))))
(defn- rand-range
[rnd lower upper]
{:pre [(<= lower upper)]}
(calc-long (random/rand-double rnd) lower upper))
(defn sized
"Creates a generator that depends on the size parameter.
`sized-gen` is a function that takes an integer and returns
a generator.
Examples:
;; generates vectors of booleans where the length always exactly
;; matches the `size` parameter
(gen/sample (gen/sized (fn [size] (gen/vector gen/boolean size))))
=> ([]
[false]
[true true]
[false true false]
[false true true true]
[false false true true false]
[false true false true true false]
[true false true true true false false]
[true true false false false true false false]
[false false false true true false true false true])"
[sized-gen]
(make-gen
(fn [rnd size]
(core/let [sized-gen (sized-gen size)]
(call-gen sized-gen rnd size)))))
;; Combinators and helpers
;; ---------------------------------------------------------------------------
(defn resize
"Creates a new generator with `size` always bound to `n`.
(gen/sample (gen/set (gen/resize 200 gen/double)))
=> (#{}
#{-4.994772362980037E147}
#{-4.234418056487335E-146}
#{}
#{}
#{}
#{NaN}
#{8.142414100982609E-63}
#{-3.58429955903876E-159 2.8563794617604296E-154
4.1021360195776005E-100 1.9084564045332549E-38}
#{-2.1582818131881376E83 -5.8460065493236117E48 9.729260993803226E166})"
[n generator]
(assert (generator? generator) "Second arg to resize must be a generator")
(core/let [{:keys [gen]} generator]
(make-gen
(fn [rnd _size]
(gen rnd n)))))
(defn scale
"Creates a new generator that modifies the size parameter by the
given function. Intended to support generators with sizes that need
to grow at different rates compared to the normal linear scaling.
(gen/sample (gen/tuple (gen/scale #(/ % 10) gen/nat)
gen/nat
(gen/scale #(* % 10) gen/nat)))
=> ([0 0 0] [0 1 2] [0 2 13] [0 1 6] [0 1 23]
[0 2 42] [0 1 26] [0 1 12] [0 1 12] [0 0 3])"
{:added "0.8.0"}
([f generator]
(sized (fn [n] (resize (f n) generator)))))
(defn choose
#?(:clj
"Creates a generator that generates integers uniformly in the range
`lower` to `upper`, inclusive.
(gen/sample (gen/choose 200 800))
=> (331 241 593 339 643 718 688 473 247 694)"
:cljs
"Creates a generator that generates integer numbers uniformly in
the range `lower` to `upper`, inclusive.
(gen/sample (gen/choose 200 800))
=> (331 241 593 339 643 718 688 473 247 694)")
[lower upper]
;; cast to long to support doubles as arguments per TCHECK-73
(core/let #?(:clj
[lower (long lower)
upper (long upper)]
:cljs ;; does nothing, no long in cljs
[])
(make-gen
(fn [rnd _size]
(core/let [value (rand-range rnd lower upper)]
(rose/filter
#(and (>= % lower) (<= % upper))
(int-rose-tree value)))))))
(defn one-of
"Creates a generator that randomly chooses a value from the list of
provided generators. Shrinks toward choosing an earlier generator,
as well as shrinking the value generated by the chosen generator.
(gen/sample (gen/one-of [gen/small-integer gen/boolean (gen/vector gen/small-integer)]))
=> (true [] -1 [0] [1 -4 -4 1] true 4 [] 6 true)"
[generators]
(assert (every? generator? generators)
"Arg to one-of must be a collection of generators")
(assert (seq generators)
"one-of cannot be called with an empty collection")
(bind (choose 0 (dec (count generators)))
#(nth generators %)))
(defn- pick
"Returns an index into the `likelihoods` sequence."
[likelihoods n]
(->> likelihoods
(reductions + 0)
(rest)
(take-while #(<= % n))
(count)))
(defn frequency
"Creates a generator that chooses a generator from `pairs` based on the
provided likelihoods. The likelihood of a given generator being chosen is
its likelihood divided by the sum of all likelihoods. Shrinks toward
choosing an earlier generator, as well as shrinking the value generated
by the chosen generator.
Examples:
(gen/sample (gen/frequency [[5 gen/small-integer] [3 (gen/vector gen/small-integer)] [2 gen/boolean]]))
=> (true [] -1 [0] [1 -4 -4 1] true 4 [] 6 true)"
[pairs]
(assert (every? (fn [[x g]] (and (number? x) (generator? g)))
pairs)
"Arg to frequency must be a list of [num generator] pairs")
(core/let [pairs (filter (comp pos? first) pairs)
total (apply + (core/map first pairs))]
(assert (seq pairs)
"frequency must be called with at least one non-zero weight")
;; low-level impl for shrinking control
(make-gen
(fn [rnd size]
(call-gen
(gen-bind (choose 0 (dec total))
(fn [x]
(core/let [idx (pick (core/map first pairs) (rose/root x))]
(gen-fmap (fn [rose]
(rose/make-rose (rose/root rose)
(lazy-seq
(concat
;; try to shrink to earlier generators first
(for [idx (range idx)]
(call-gen (second (nth pairs idx))
rnd
size))
(rose/children rose)))))
(second (nth pairs idx))))))
rnd size)))))
(defn elements
"Creates a generator that randomly chooses an element from `coll`.
(gen/sample (gen/elements [:foo :bar :baz]))
=> (:foo :baz :baz :bar :foo :foo :bar :bar :foo :bar)"
[coll]
(assert (seq coll) "elements cannot be called with an empty collection")
(core/let [v (vec coll)]
(gen-fmap #(rose/fmap v %)
(choose 0 (dec (count v))))))
(defn- such-that-helper
[pred gen {:keys [ex-fn max-tries]} rng size]
(loop [tries-left max-tries
rng rng
size size]
(if (zero? tries-left)
(throw (ex-fn {:pred pred, :gen, gen :max-tries max-tries}))
(core/let [[r1 r2] (random/split rng)
value (call-gen gen r1 size)]
(if (pred (rose/root value))
(rose/filter pred value)
(recur (dec tries-left) r2 (inc size)))))))
(def ^:private
default-such-that-opts
{:ex-fn (fn [{:keys [max-tries] :as arg}]
(ex-info (str "Couldn't satisfy such-that predicate after "
max-tries " tries.")
arg))
:max-tries 10})
(defn such-that
"Creates a generator that generates values from `gen` that satisfy predicate
`pred`. Care is needed to ensure there is a high chance `gen` will satisfy
`pred`. By default, `such-that` will try 10 times to generate a value that
satisfies the predicate. If no value passes this predicate after this number
of iterations, a runtime exception will be thrown. Note also that each
time such-that retries, it will increase the size parameter.
Examples:
;; generate non-empty vectors of integers
;; (note, gen/not-empty does exactly this)
(gen/such-that not-empty (gen/vector gen/small-integer))
You can customize `such-that` by passing an optional third argument, which can
either be an integer representing the maximum number of times test.check
will try to generate a value matching the predicate, or a map:
:max-tries positive integer, the maximum number of tries (default 10)
:ex-fn a function of one arg that will be called if test.check cannot
generate a matching value; it will be passed a map with `:gen`,
`:pred`, and `:max-tries` and should return an exception"
([pred gen]
(such-that pred gen 10))
([pred gen max-tries-or-opts]
(core/let [opts (cond (integer? max-tries-or-opts)
{:max-tries max-tries-or-opts}
(map? max-tries-or-opts)
max-tries-or-opts
:else
(throw (ex-info "Bad argument to such-that!" {:max-tries-or-opts
max-tries-or-opts})))
opts (merge default-such-that-opts opts)]
(assert (generator? gen) "Second arg to such-that must be a generator")
(make-gen
(fn [rand-seed size]
(such-that-helper pred gen opts rand-seed size))))))
(defn not-empty
"Modifies a generator so that it doesn't generate empty collections.
Examples:
;; generate a vector of booleans, but never the empty vector
(gen/sample (gen/not-empty (gen/vector gen/boolean)))
=> ([false]
[false false]
[false false]
[false false false]
[false false false false]
[false true true]
[true false false false]
[true]
[true true true false false true false]
[false true true true false true true true false])"
[gen]
(assert (generator? gen) "Arg to not-empty must be a generator")
(such-that core/not-empty gen))
(defn no-shrink
"Creates a new generator that is just like `gen`, except does not shrink
at all. This can be useful when shrinking is taking a long time or is not
applicable to the domain."
[gen]
(assert (generator? gen) "Arg to no-shrink must be a generator")
(gen-fmap (fn [rose]
(rose/make-rose (rose/root rose) []))
gen))
(defn shrink-2
"Creates a new generator like `gen`, but will consider nodes for shrinking
even if their parent passes the test (up to one additional level)."
[gen]
(assert (generator? gen) "Arg to shrink-2 must be a generator")
(gen-fmap rose/collapse gen))
(def boolean
"Generates one of `true` or `false`. Shrinks to `false`."
(elements [false true]))
(defn tuple
"Creates a generator that returns a vector, whose elements are chosen
from the generators in the same position. The individual elements shrink
according to their generator, but the vector will never shrink in count.
Examples:
(def t (gen/tuple gen/small-integer gen/boolean))
(sample t)
;; => ([1 true] [2 true] [2 false] [1 false] [0 true] [-2 false] [-6 false]
;; => [3 true] [-4 false] [9 true]))"
[& generators]
(assert (every? generator? generators)
"Args to tuple must be generators")
(gen-fmap (fn [roses]
(rose/zip core/vector roses))
(gen-tuple generators)))
(def nat
"Generates non-negative integers bounded by the generator's `size`
parameter. Shrinks to zero."
(sized (fn [size] (choose 0 size)))
#_
(fmap #(Math/abs (long %)) int))
(def ^{:added "0.10.0"} small-integer
"Generates a positive or negative integer bounded by the generator's
`size` parameter. Shrinks to zero."
(sized (fn [size] (choose (- size) size))))
;; The following five are deprecated due to being confusingly named,
;; and in some cases not being very useful.
(def ^{:deprecated "0.10.0"} int
"Deprecated - use gen/small-integer instead.
Generates a positive or negative integer bounded by the generator's
`size` parameter."
small-integer)
(def ^{:deprecated "0.10.0"} pos-int
"Deprecated - use gen/nat instead (see also gen/large-integer).
(this generator, despite its name, can generate 0)
Generates nonnegative integers bounded by the generator's `size` parameter."
nat)
(def ^{:deprecated "0.10.0"} neg-int
"Deprecated - use (gen/fmap - gen/nat) instead (see also gen/large-integer).
(this generator, despite its name, can generate 0)
Generates nonpositive integers bounded by the generator's `size` parameter."
(fmap #(* -1 %) nat))
(def ^{:deprecated "0.10.0"} s-pos-int
"Deprecated - use (gen/fmap inc gen/nat) instead (see also gen/large-integer).
Generates positive integers bounded by the generator's `size` + 1"
(fmap inc nat))
(def ^{:deprecated "0.10.0"} s-neg-int
"Deprecated - use (gen/fmap (comp dec -) gen/nat) instead (see also gen/large-integer).
Generates negative integers bounded by the generator's `size` + 1"
(fmap dec neg-int))
(defn vector
"Creates a generator of vectors whose elements are chosen from
`generator`. The count of the vector will be bounded by the `size`
generator parameter."
([generator]
(assert (generator? generator) "Arg to vector must be a generator")
(gen-bind
(sized #(choose 0 %))
(fn [num-elements-rose]
(gen-fmap (fn [roses]
(rose/shrink-vector core/vector
roses))
(gen-tuple (repeat (rose/root num-elements-rose)
generator))))))
([generator num-elements]
(assert (generator? generator) "First arg to vector must be a generator")
(apply tuple (repeat num-elements generator)))
([generator min-elements max-elements]
(assert (generator? generator) "First arg to vector must be a generator")
(gen-bind
(choose min-elements max-elements)
(fn [num-elements-rose]
(gen-fmap (fn [roses]
(rose/filter
(fn [v] (and (>= (count v) min-elements)
(<= (count v) max-elements)))
(rose/shrink-vector core/vector
roses)))
(gen-tuple (repeat (rose/root num-elements-rose)
generator)))))))
(defn list
"Like `vector`, but generates lists."
[generator]
(assert (generator? generator) "First arg to list must be a generator")
(gen-bind (sized #(choose 0 %))
(fn [num-elements-rose]
(gen-fmap (fn [roses]
(rose/shrink-vector core/list
roses))
(gen-tuple (repeat (rose/root num-elements-rose)
generator))))))
(defn- swap
[coll [i1 i2]]
(assoc coll i2 (coll i1) i1 (coll i2)))
(defn
^{:added "0.6.0"}
shuffle
"Creates a generator that generates random permutations of
`coll`. Shrinks toward the original collection: `coll`. `coll` will
be coerced to a vector."
[coll]
(core/let [coll (if (vector? coll) coll (vec coll))
index-gen (choose 0 (dec (count coll)))]
(fmap #(reduce swap coll %)
;; a vector of swap instructions, with count between
;; zero and 2 * count. This means that the average number
;; of instructions is count, which should provide sufficient
;; (though perhaps not 'perfect') shuffling. This still gives us
;; nice, relatively quick shrinks.
(vector (tuple index-gen index-gen) 0 (* 2 (count coll))))))
;; NOTE cljs: Comment out for now - David
#?(:clj
(def byte
"Generates `java.lang.Byte`s, using the full byte-range."
(fmap core/byte (choose Byte/MIN_VALUE Byte/MAX_VALUE))))
#?(:clj
(def bytes
"Generates byte-arrays."
(fmap core/byte-array (vector byte))))
(defn hash-map
"Like clojure.core/hash-map, except the values are generators.
Returns a generator that makes maps with the supplied keys and
values generated using the supplied generators.
(gen/sample (gen/hash-map :a gen/boolean :b gen/nat))
=> ({:a false, :b 0}
{:a true, :b 1}
{:a false, :b 2}
{:a true, :b 2}
{:a false, :b 4}
{:a false, :b 2}
{:a true, :b 3}
{:a true, :b 4}
{:a false, :b 1}
{:a false, :b 0})"
[& kvs]
(assert (even? (count kvs)))
(core/let [ks (take-nth 2 kvs)
vs (take-nth 2 (rest kvs))]
(assert (every? generator? vs)
"Value args to hash-map must be generators")
(fmap #(zipmap ks %)
(apply tuple vs))))
;; Collections of distinct elements
;; (has to be done in a low-level way (instead of with combinators)
;; and is subject to the same kind of failure as such-that)
;; ---------------------------------------------------------------------------
(defn ^:private transient-set-contains?
[s k]
#? (:clj
(.contains ^clojure.lang.ITransientSet s k)
:cljs
(some? (-lookup s k))))
(defn ^:private coll-distinct-by*
"Returns a rose tree."
[empty-coll key-fn shuffle-fn gen rng size num-elements min-elements max-tries ex-fn]
{:pre [gen (:gen gen)]}
(loop [rose-trees (transient [])
s (transient #{})
rng rng
size size
tries 0]
(cond (and (= max-tries tries)
(< (count rose-trees) min-elements))
(throw (ex-fn {:gen gen
:max-tries max-tries
:num-elements num-elements}))
(or (= max-tries tries)
(= (count rose-trees) num-elements))
(->> (persistent! rose-trees)
;; we shuffle the rose trees so that we aren't biased
;; toward generating "smaller" elements earlier in the
;; collection (only applies to ordered collections)
;;
;; shuffling the rose trees is more efficient than
;; (bind ... shuffle) because we only perform the
;; shuffling once and we have no need to shrink the
;; shufling.
(shuffle-fn rng)
(rose/shrink-vector #(into empty-coll %&)))
:else
(core/let [[rng1 rng2] (random/split rng)
rose (call-gen gen rng1 size)
root (rose/root rose)
k (key-fn root)]
(if (transient-set-contains? s k)
(recur rose-trees s rng2 (inc size) (inc tries))
(recur (conj! rose-trees rose)
(conj! s k)
rng2
size
0))))))
(defn ^:private distinct-by?
"Like clojure.core/distinct? but takes a collection instead of varargs,
and returns true for empty collections."
[f coll]
(or (empty? coll)
(apply distinct? (core/map f coll))))
(defn ^:private the-shuffle-fn
"Returns a shuffled version of coll according to the rng.
Note that this is not a generator, it is just a utility function."
[rng coll]
(core/let [empty-coll (empty coll)
v (vec coll)
card (count coll)
dec-card (dec card)]
(into empty-coll
(first
(reduce (fn [[v rng] idx]
(core/let [[rng1 rng2] (random/split rng)
swap-idx (rand-range rng1 idx dec-card)]
[(swap v [idx swap-idx]) rng2]))
[v rng]
(range card))))))
(defn ^:private coll-distinct-by
[empty-coll key-fn allows-dupes? ordered? gen
{:keys [num-elements min-elements max-elements max-tries ex-fn]
:or {max-tries 10
ex-fn #(ex-info "Couldn't generate enough distinct elements!" %)}}]
(core/let [shuffle-fn (if ordered?
the-shuffle-fn
(fn [_rng coll] coll))
hard-min-elements (or num-elements min-elements 1)]
(if num-elements
(core/let [size-pred #(= num-elements (count %))]
(assert (and (nil? min-elements) (nil? max-elements)))
(make-gen
(fn [rng gen-size]
(rose/filter
(if allows-dupes?
;; is there a smarter way to do the shrinking than checking
;; the distinctness of the entire collection at each
;; step?
(every-pred size-pred #(distinct-by? key-fn %))
size-pred)
(coll-distinct-by* empty-coll key-fn shuffle-fn gen rng gen-size
num-elements hard-min-elements max-tries ex-fn)))))
(core/let [min-elements (or min-elements 0)
size-pred (if max-elements
#(<= min-elements (count %) max-elements)
#(<= min-elements (count %)))]
(gen-bind
(if max-elements
(choose min-elements max-elements)
(sized #(choose min-elements (+ min-elements %))))
(fn [num-elements-rose]
(core/let [num-elements (rose/root num-elements-rose)]
(make-gen
(fn [rng gen-size]
(rose/filter
(if allows-dupes?
;; same comment as above
(every-pred size-pred #(distinct-by? key-fn %))
size-pred)
(coll-distinct-by* empty-coll key-fn shuffle-fn gen rng gen-size
num-elements hard-min-elements max-tries ex-fn)))))))))))
;; I tried to reduce the duplication in these docstrings with a macro,
;; but couldn't make it work in cljs.
(defn vector-distinct
"Generates a vector of elements from the given generator, with the
guarantee that the elements will be distinct.
If the generator cannot or is unlikely to produce enough distinct
elements, this generator will fail in the same way as `such-that`.
Available options:
:num-elements the fixed size of generated vectors
:min-elements the min size of generated vectors
:max-elements the max size of generated vectors
:max-tries the number of times the generator will be tried before
failing when it does not produce distinct elements
(default 10)
:ex-fn a function of one arg that will be called if test.check cannot
generate enough distinct values; it will be passed a map with
`:gen`, `:num-elements`, and `:max-tries` and should return an
exception"
{:added "0.9.0"}
([gen] (vector-distinct gen {}))
([gen opts]
(assert (generator? gen) "First arg to vector-distinct must be a generator!")
(coll-distinct-by [] identity true true gen opts)))
(defn list-distinct
"Generates a list of elements from the given generator, with the
guarantee that the elements will be distinct.
If the generator cannot or is unlikely to produce enough distinct
elements, this generator will fail in the same way as `such-that`.
Available options:
:num-elements the fixed size of generated list
:min-elements the min size of generated list
:max-elements the max size of generated list
:max-tries the number of times the generator will be tried before
failing when it does not produce distinct elements
(default 10)
:ex-fn a function of one arg that will be called if test.check cannot
generate enough distinct values; it will be passed a map with
`:gen`, `:num-elements`, and `:max-tries` and should return an
exception"
{:added "0.9.0"}
([gen] (list-distinct gen {}))
([gen opts]
(assert (generator? gen) "First arg to list-distinct must be a generator!")
(coll-distinct-by () identity true true gen opts)))
(defn vector-distinct-by
"Generates a vector of elements from the given generator, with the
guarantee that (map key-fn the-vector) will be distinct.
If the generator cannot or is unlikely to produce enough distinct
elements, this generator will fail in the same way as `such-that`.
Available options:
:num-elements the fixed size of generated vectors
:min-elements the min size of generated vectors
:max-elements the max size of generated vectors
:max-tries the number of times the generator will be tried before
failing when it does not produce distinct elements
(default 10)
:ex-fn a function of one arg that will be called if test.check cannot
generate enough distinct values; it will be passed a map with
`:gen`, `:num-elements`, and `:max-tries` and should return an
exception"
{:added "0.9.0"}
([key-fn gen] (vector-distinct-by key-fn gen {}))
([key-fn gen opts]
(assert (generator? gen) "Second arg to vector-distinct-by must be a generator!")
(coll-distinct-by [] key-fn true true gen opts)))
(defn list-distinct-by
"Generates a list of elements from the given generator, with the
guarantee that (map key-fn the-list) will be distinct.
If the generator cannot or is unlikely to produce enough distinct
elements, this generator will fail in the same way as `such-that`.
Available options:
:num-elements the fixed size of generated list
:min-elements the min size of generated list
:max-elements the max size of generated list
:max-tries the number of times the generator will be tried before
failing when it does not produce distinct elements
(default 10)
:ex-fn a function of one arg that will be called if test.check cannot
generate enough distinct values; it will be passed a map with
`:gen`, `:num-elements`, and `:max-tries` and should return an
exception"
{:added "0.9.0"}
([key-fn gen] (list-distinct-by key-fn gen {}))
([key-fn gen opts]
(assert (generator? gen) "Second arg to list-distinct-by must be a generator!")
(coll-distinct-by () key-fn true true gen opts)))
(defn set
"Generates a set of elements from the given generator.
If the generator cannot or is unlikely to produce enough distinct
elements, this generator will fail in the same way as `such-that`.
Available options:
:num-elements the fixed size of generated set
:min-elements the min size of generated set
:max-elements the max size of generated set
:max-tries the number of times the generator will be tried before
failing when it does not produce distinct elements
(default 10)
:ex-fn a function of one arg that will be called if test.check cannot
generate enough distinct values; it will be passed a map with
`:gen`, `:num-elements`, and `:max-tries` and should return an
exception"
{:added "0.9.0"}
([gen] (set gen {}))
([gen opts]
(assert (generator? gen) "First arg to set must be a generator!")
(coll-distinct-by #{} identity false false gen opts)))
(defn sorted-set
"Generates a sorted set of elements from the given generator.
If the generator cannot or is unlikely to produce enough distinct
elements, this generator will fail in the same way as `such-that`.
Available options:
:num-elements the fixed size of generated set
:min-elements the min size of generated set
:max-elements the max size of generated set
:max-tries the number of times the generator will be tried before
failing when it does not produce distinct elements
(default 10)
:ex-fn a function of one arg that will be called if test.check cannot
generate enough distinct values; it will be passed a map with
`:gen`, `:num-elements`, and `:max-tries` and should return an
exception"
{:added "0.9.0"}
([gen] (sorted-set gen {}))
([gen opts]
(assert (generator? gen) "First arg to sorted-set must be a generator!")
(coll-distinct-by (core/sorted-set) identity false false gen opts)))
(defn map
"Creates a generator that generates maps, with keys chosen from
`key-gen` and values chosen from `val-gen`.
If the key generator cannot or is unlikely to produce enough distinct
elements, this generator will fail in the same way as `such-that`.
Available options:
:num-elements the fixed size of generated maps
:min-elements the min size of generated maps
:max-elements the max size of generated maps
:max-tries the number of times the generator will be tried before
failing when it does not produce distinct elements
(default 10)
:ex-fn a function of one arg that will be called if test.check cannot
generate enough distinct keys; it will be passed a map with
`:gen` (the key-gen), `:num-elements`, and `:max-tries` and
should return an exception"
([key-gen val-gen] (map key-gen val-gen {}))
([key-gen val-gen opts]
(coll-distinct-by {} first false false (tuple key-gen val-gen) opts)))
;; large integers
;; ---------------------------------------------------------------------------
;; This approach has a few distribution edge cases, but is pretty good
;; for expected uses and is way better than nothing.
(def ^:private gen-raw-long
"Generates a single uniformly random long, does not shrink."
(make-gen (fn [rnd _size]
(rose/pure (random/rand-long rnd)))))
(def ^:private MAX_INTEGER
#?(:clj Long/MAX_VALUE :cljs (dec (apply * (repeat 53 2)))))
(def ^:private MIN_INTEGER
#?(:clj Long/MIN_VALUE :cljs (- MAX_INTEGER)))