Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test.check generate strings of a certain length

In using test.check I need a generator for strings of a certain length. Phone numbers, postal codes, social security numbers are all examples of this type of data. Although the examples appear to be only numbers, my question is for strings in general.

like image 920
M Smith Avatar asked Dec 25 '22 08:12

M Smith


2 Answers

Given length the generator below generates random strings:

(gen/fmap #(apply str %) 
          (gen/vector gen/char-alpha length))

(gen/vector gen/char-alpha length) generates sequences of characters and the fmap converts them into strings:

(apply str [\a \b]) ;; => "ab"

If a custom alphabet (say [\a \b \c]) is needed gen/char-alpha can be substituted with something like:

(gen/elements alphabet)

For more complex generators, like formatted phone numbers, test.chuck's string-from-regex might be a better choice than manually combining official generators.

like image 103
muhuk Avatar answered Jan 11 '23 23:01

muhuk


This function will generate a string of a given length with characters from a given alphabet (optional). If you don't pass any alphabet as an argument, a default will be used, which you can of course change.

(defn generate-string 
  ([length]
   (generate-string length
            (map char (range 49 127))))
  ([length alphabet]
   (apply str (take length (repeatedly #(rand-nth alphabet))))))

Examples:

(generate-string 7 [\a \b \c])
"bacacbb"

(generate-string 10)
"mxqE<OKH3L"
like image 39
MicSokoli Avatar answered Jan 11 '23 23:01

MicSokoli