Search code examples
.netf#fscheck

How to make FsCheck generate random strings that respect MaxLengthAttribute?


Is it possible for FsCheck to generate random records that respect the MaxLengthAttribute. Example record type:

type Person =
    {
        Id: int
        [<System.ComponentModel.DataAnnotations.MaxLength(256)>]
        FirstName: string
        [<System.ComponentModel.DataAnnotations.MaxLength(256)>]
        LastName: string
    }

Solution

  • Not out of the box, but you can do something like:

    Arb.generate<Person> 
    |> Gen.where (fun p -> p.FirstName.Length <= 256 && p.LastName.Length <= 256)
    

    Then it's a matter of creating the predicate for Gen.where based on the type of the thing passed in, i.e. use reflection to find the properties that have the MaxLength attribute, get out the value and restrict the length.

    Note also that by default the max length of generated strings for generating 100 values per tests is 50, so this may be moot.