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.
test.check generate strings of a certain length
2.1k Views Asked by M Smith At
3
There are 3 best solutions below
1
On
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"
3
On
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))
Given
length
the generator below generates random strings:(gen/vector gen/char-alpha length)
generates sequences of characters and thefmap
converts them into strings:If a custom
alphabet
(say[\a \b \c]
) is neededgen/char-alpha
can be substituted with something like:For more complex generators, like formatted phone numbers, test.chuck's
string-from-regex
might be a better choice than manually combining official generators.