Skip to content

String not-regex constraint succeeds non-string actual value #4484

Closed

Description

@RenderMichael

The following code passes

[Test]
public void StringMatchesRegex()
{
    // lang=regex
    string regex = "[0-9]";
    string? actual = null;
    Assert.That(actual, Does.Not.Match(regex));
}

Should the RegexConstraint throw an ArgumentException for non-string values (like null)?

If so, that a 2-line change (plus tests) and I can spin up the PR myself.

Activity

  1. OsirisTerje commented on Oct 9, 2023

    @OsirisTerje
    Member

    Well,.... null does not match any regex, so the statement there is true.

    You could try:

    Assert.That(actual, Is.Not.Null.And.Does.Not.Match(regex));
  2. RenderMichael commented on Oct 10, 2023

    @RenderMichael
    ContributorAuthor

    null does not match any regex

    That's a philosophical statement, and I see the point.

    On the other hand, .NET's built-in regex throws when calling Matches(null).

    Additionally, the constraint calls actual is string actualStr && Regex.Matches(actualStr) (pseudocode since I don't have the code in front of me).

    So the following also passes, although it's flagged by NUnit.Analyzers

    [Test]
    public void StringMatchesRegex()
    {
        // lang=regex
        string regex = "[0-9]";
        int actual = 1;
        Assert.That(actual, Does.Not.Match(regex));
    }

    edit: in fact, that's good broadening of the issue, I'll rename it

  3. changed the title [-]String not-regex constraint succeeds on `null` actual value[/-] [+]String not-regex constraint succeeds non-`string` actual value[/+] on Oct 10, 2023
  4. OsirisTerje commented on Oct 10, 2023

    @OsirisTerje
    Member

    On the other hand, .NET's built-in regex throws when calling Matches(null)

    If .Net does so, we should probably do the same.

  5. RenderMichael commented on Oct 10, 2023

    @RenderMichael
    ContributorAuthor

    Would love to be assigned this PBI, I can spin up a PR for it

  6. OsirisTerje commented on Oct 10, 2023

    @OsirisTerje
    Member

    There you are :-) Have fun!

  7. added this to the 4.0 milestone on Oct 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions