Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scalacheck: Generate a non empty string

What is the best way to generate a non empty string, when in the context of something like this

  private def createIndexFn() = {
      for{
        someChar <-  Gen.alphaString
        aNumber <- Gen.choose(1,100)
        //...
       }       
       yield { 
           MyThing(AnotherType(someChar.toString), SomeOtherType(aNumber), aNumber)
   }
 }

where you need maybe someChar to be a non empty string. I know you can use whenever in the forAll section but I wonder how to do it in this part of the generator.

Thanks

like image 948
roundcrisis Avatar asked Aug 24 '16 14:08

roundcrisis


3 Answers

The accepted answer caused a high ratio of discarded tests for me, I ended up using:

import org.scalacheck._

Arbitrary(Gen.nonEmptyListOf[Char](Arbitrary.arbChar.arbitrary)).map(_.mkString))
like image 93
Matthew Pickering Avatar answered Nov 05 '22 09:11

Matthew Pickering


Another way is to create a fix length random string

Gen.listOfN(10, Gen.asciiPrintableChar).map(_.mkString)

or to create a random length with a constrained length

for {
  n     <- Gen.chooseNum(5, 20)
  chars <- Gen.listOfN(n, Gen.asciiPrintableChar)
} yield chars.mkString
like image 41
Channing Walton Avatar answered Nov 05 '22 09:11

Channing Walton


What I was looking for was:

import org.scalacheck.Arbitrary.arbitrary

arbitrary[String].suchThat(!_.isEmpty)

and can be used like

for {
  name <- arbitrary[String].suchThat(!_.isEmpty)
  age  <- Gen.choose(0, 100)
} yield Person(name, age)

Hopefully this helps someone

like image 13
roundcrisis Avatar answered Nov 05 '22 09:11

roundcrisis