2

I have this generator that seems to work, but when I check the values generated, it never picks the null value. How does one write generator that will pick null value. This code never picks null value for "end" date.

public static Gen<DateTime?> NullableDateTimeGen()
    {
        var list = new List<DateTime?>();

        if (list.Any() == false)
        {
            var endDate = DateTime.Now.AddDays(5);
            var startDate = DateTime.Now.AddDays(-10);

            list.AddRange(Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days)
                .Select(offset => startDate.AddDays(offset))
                .Cast<DateTime?>()
                .ToList());

            list.Add(null);
            list.Insert(0, null);
        }

        return from i in Gen.Choose(0, list.Count - 1)
               select list[i];
    }

    public static Arbitrary<Tuple<DateRange, DateTime>> TestTuple()
    {
        return (from s in NullableDateTimeGen().Where(x => x != null)
                from e in NullableDateTimeGen()
                from p in NullableDateTimeGen().Where(x => x != null)
                where s <= e
                select new Tuple<DateRange, DateTime>(new DateRange(s.Value, e), p.Value))
                .ToArbitrary();
    }
epitka
  • 17,275
  • 20
  • 88
  • 141

1 Answers1

1

The problem is not related to FsCheck and is in this statement:

from s in NullableDateTimeGen().Where(x => x != null)
            from e in NullableDateTimeGen()
            from p in NullableDateTimeGen().Where(x => x != null)
            where s <= e
            select new Tuple<DateRange, DateTime>(new DateRange(s.Value, e), p.Value))

Note that you filter nulls from s and p, so they are never null. The only thing that can be null if e. However, you do

where s <= e

This comparision can never be true if e is null, because anything compared with null is always false. So you filter out null values for e also.

To fix just replace that condition with whatever makes sense for your scenario, like

where e == null || s <= e
Evk
  • 98,527
  • 8
  • 141
  • 191