3
votes

I'm new to FsCheck and I need an array of json to perform my tests.

I want a simple solution like the following:

let commaSeparated =  Gen.arrayOf Arb.generate<string> 
                      |> Gen.fold(fun (acc,i)-> i+="\",\"")
                      |> Gen.finalValueOf
                      |> StringExtensions.skipLastChar
let result = Arb.from "[\"" + commaSeparated +"\"]"

But the main problem is that I can't find Gen.fold and Gen.finalValueOf.

1

1 Answers

2
votes

I'm no expert on FsCheck either, but I think there is some weird stuff going on in your code apart from the missing functions. What's StringExtensions.skipLastChar doing? Also I don't think Gens can be concatenated with strings like you are trying to in the last line. What's Gen.finalValueOf supposed to do?

I got your example working (not sure if it does what you need it to) using Gen.map to join the strings to a comma separated list and wrap the result in brackets:

let jsonArray = 
    Arb.generate<string>
    |> Gen.arrayOf  
    |> Gen.map (String.concat "\",\"")
    |> Gen.map (fun strs -> "[\"" + strs + "\"]")

let result = Arb.fromGen jsonArray

By the way: I think you need to consider generated double quotes. If you don't escape them your JSON parser will fail. Below is a version of jsonArray that does that:

let escapeDoubleQuotes (str:string) = str.Replace ("\"", "\\\"")

let jsonArray = 
    Arb.generate<string>
    |> Gen.arrayOf
    |> Gen.map (Array.map escapeDoubleQuotes)
    |> Gen.map (String.concat "\", \"")
    |> Gen.map (fun strs -> "[\"" + strs + "\"]")