Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
RenderMichael opened this issue Oct 8, 2023 · 5 comments · Fixed by #4492
Closed

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

RenderMichael opened this issue Oct 8, 2023 · 5 comments · Fixed by #4492
Assignees
Milestone

Comments

@RenderMichael
Copy link
Contributor

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.

@OsirisTerje
Copy link
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));

@RenderMichael
Copy link
Contributor Author

RenderMichael commented Oct 10, 2023

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

@RenderMichael RenderMichael changed the title String not-regex constraint succeeds on null actual value String not-regex constraint succeeds non-string actual value Oct 10, 2023
@OsirisTerje
Copy link
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.

@RenderMichael
Copy link
Contributor Author

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

@OsirisTerje
Copy link
Member

There you are :-) Have fun!

@OsirisTerje OsirisTerje added this to the 4.0 milestone Oct 10, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants