Monday, March 8, 2010

Lazy man's random test data

A quick tip for generating some random testdata.

Note: This is a poor man's solution to using ScalaCheck. If you can handle the dependency I would really recommend using that library.

  1. scala> object Options extends Enumeration {                       
  2.      | val ONE, TWO, THREE, FOUR = Value                          
  3.      | }
  4. defined module Options
  5. /*
  6. Randomly select zero or more elements from the options enumeration
  7. */
  8. scala> Options.values.filter {_ => util.Random.nextBoolean} mkString ", "
  9. res2: String = TWO, FOUR
  10. /*
  11. Select a random string.  
  12. Warning:  there is no restriction on the characters so control characters are likely
  13. */
  14. scala> util.Random.nextString(10)
  15. res5: String = ??????????
  16. /*
  17. ASCII string is oftern more useful for test data.  This selects a random string up to 13 characters long
  18. */
  19. scala> util.Random.nextASCIIString(13)
  20. res6: java.lang.String = RVPD\#_HqJ8:o
  21. /*
  22. This creates a sequence of 10 random strings
  23. */
  24. scala> 1 to 10 map {_ => util.Random.nextASCIIString(13)}
  25. res7: scala.collection.immutable.IndexedSeq[java.lang.String] = IndexedSeq(;E8|Q8H8RI;Q=, vM-X;"ksBr\:c, SKyz{uXNQ5E]X, =Jd8_ll08)s%e, gRCs)6wj%C-YF, `x;2Zru?l*c%@, XE*/Rx9:qPfpm, s|u,e.un+-Xm(, M,TpX9Dq-6$+^, w;exER&#0|}Ya)

1 comment:

  1. Some of my handwritten stuff :)

    def randAlphaString(nchars: Int = 32) = scala.util.Random.alphanumeric.filter(_.isLetter).take(nchars).mkString

    def randString(nchars: Int = 32) = UUID.randomUUID.toString.replaceAll("-", "").take(nchars)

    def randDate(from: Long = 0, until: Long = nowInMillis) = {
    require(from <= until, "From can't be greater than Until for date range.")
    new Date((from + Random.nextDouble * (until - from)).toLong)
    }

    def randEnum(enum: Enumeration) = enum(Random.nextInt(enum.maxId))

    ReplyDelete