Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not empty string generator with FsCheck using c# fluent interface

I'm trying to create a not empty string generator but when running the test I still have empty strings as inputs.

Here is the code I wrote:

    [Test]
    public void MyTest()
    {
        Func<Gen<string>> generateNotEmptyString = () =>
        {
            var gen = Any.OfType<string>()
                         .Where(name => !string.IsNullOrEmpty(name));
            return gen;
        };

        Action<string> assertIdIsNeverEmpty = name =>
        {
                var id = MyService.CreateId(name);
                id.Should().NotBeNullOrEmpty();
        };

        Spec.For(generateNotEmptyString(), assertIdIsNeverEmpty)
            .QuickCheckThrowOnFailure()
    }

I'm using NUnit v. 2.6.2.12296, FsCheck v. 0.9.4.0 and FluentAssertions v. 3.0.90.0.

What if I also want to modify the generator so that it creates not empty strings that match a regular expression?

[EDIT] This is the code I'm using to create strings that contain letters but don't contain special characters:

    private static Gen<NonEmptyString> GenerateValidNames()
    {
        return
            Any.OfType<NonEmptyString>()
                .Where(s =>
                    !s.Get.Contains("\r") &&
                    !s.Get.Contains("\n") &&
                    !s.Get.Contains("\t"))
                .Where(s =>
                {
                    var regEx = new Regex(@"^[A-Za-z]*$");
                    return regEx.Match(s.Get).Success;
                });            
    }

1 Answers

Maybe you have a bug :) The following works for me:

    public void MyTest()
    {
        Gen<string> generateNotEmptyString = Any.OfType<string>()
                                                .Where(name => !string.IsNullOrEmpty(name));

        Action<string> assertIdIsNeverEmpty = name =>
        {
                Assert.False(String.IsNullOrEmpty(name));
        };

        Spec.For(generateNotEmptyString, assertIdIsNeverEmpty)
            .QuickCheckThrowOnFailure();
    }

Note you don't need the extra Func around the generator. A generator is a function already, under the covers, so just creating one won't execute any code (more or less), much like an IEnumerable.

Alternatively, use the built in non-empty string generator:

        Action<NonEmptyString> assertIdIsNeverEmpty = name =>
        {
                Assert.False(String.IsNullOrEmpty(name.Get));
        };

        Spec.For(Any.OfType<NonEmptyString>(), assertIdIsNeverEmpty)
            .QuickCheckThrowOnFailure();

Generating strings that match a regexp is a solved problem, but not straightforward. FsCheck currently has no support for it directly. Though I think it would make a great addition! See How to generate random strings that match a given regexp?

like image 200
Kurt Schelfthout Avatar answered Feb 09 '26 07:02

Kurt Schelfthout