test.check generate strings of a certain length

Viewed 1824

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.

3 Answers

You can use the more primitive generators to quickly build one that does just that:

For alphanumeric strings between min and max:

(sgen/fmap str/join (sgen/vector (sgen/char-alphanumeric) min max))

For alphanumeric strings of exactly a given length

(sgen/fmap str/join (sgen/vector (sgen/char-alphanumeric) length))

And you can modify (sgen/char-alphanumeric) accordingly to whatever your character range needs to be, such as a string of min/max with alphanumeric and underscore and dash character as well, with different frequencies of each character showing up:

(sgen/fmap str/join
                (sgen/vector
                 (sgen/frequency [[99 (sgen/char-alphanumeric)]
                                  [1 (sgen/elements #{"_" "-"})]])
                 min max))
Related