Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random string with FsCheck using C#

I'd like to gradually integrate FsCheck in my C# test code (as first step).

I'd like to randomly generate part of my input data.

This is how I generate a random string:


static string RandomString() {
  var kgen = Gen.Constant(Gen.Sized(g => Gen.OneOf(Arb.Generate())));
  var sgen = Gen.Sample(1, 10, kgen).First();
  var str = Gen.Eval(10, Random.StdGen.NewStdGen(0, 1000), sgen);
  return str;
}

If I call it multiple times, I get each time the same string.

How can I get a different string each time and/or correctly writing this code?

like image 623
gsscoder Avatar asked Aug 14 '15 15:08

gsscoder


Video Answer


1 Answers

You should replace your tests with properties, instead of trying to generate random strings and then use those in your tests manually. FsCheck is not geared towards using it as a random generator, although it is possible to coerce it to that. Something like:

var maxLength = 10
return Arb.Generate<string>().Sample(maxLength, 1).Single()

should generate a new random string of length up to 10 "most of the time", i.e. if I remember correctly the random seed is time based. So if you call it twice in the same interval it'll return the same string.

Doing it this way won't let you take advantage of shrinking and the API in Prop for example to observe and classify the generated data, and e.g. restrict it: https://fscheck.github.io/FsCheck/Properties.html

like image 164
Kurt Schelfthout Avatar answered Sep 19 '22 11:09

Kurt Schelfthout