Skip to content

Commit f771316

Browse files
authored
Merge pull request #704 from manfred-brands/issues/679_NullSuppressionOperator
Ignore null suppression operator when matching Is.Not.Null
2 parents 4798485 + 1703848 commit f771316

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/nunit.analyzers.tests/DiagnosticSuppressors/DereferencePossiblyNullReferenceSuppressorTests.cs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -997,5 +997,40 @@ public Extra(string info, int value)
997997
ExpectedDiagnostic.Create(DereferencePossiblyNullReferenceSuppressor.SuppressionDescriptors["CS8602"]),
998998
testCode);
999999
}
1000+
1001+
[Test]
1002+
public void TestNullSuppressionOperator()
1003+
{
1004+
var testCode = TestUtility.WrapMethodInClassNamespaceAndAddUsings(@"
1005+
[TestCase(default(string))]
1006+
public void Test(string ?possibleNullString)
1007+
{
1008+
HasString str = new(possibleNullString);
1009+
1010+
string nonNullString = GetStringSuppress(str);
1011+
Assert.That(nonNullString, Is.Not.Null);
1012+
}
1013+
1014+
private static string GetStringSuppress(HasString? str) // argument is nullable
1015+
{
1016+
Assert.That(str!.Inner, Is.Not.Null);
1017+
return str.Inner; // warning: possible null reference return
1018+
}
1019+
1020+
private sealed class HasString
1021+
{
1022+
public HasString(string? inner)
1023+
{
1024+
Inner = inner;
1025+
}
1026+
1027+
public string? Inner { get; }
1028+
}
1029+
");
1030+
1031+
RoslynAssert.Suppressed(suppressor,
1032+
ExpectedDiagnostic.Create(DereferencePossiblyNullReferenceSuppressor.SuppressionDescriptors["CS8603"]),
1033+
testCode);
1034+
}
10001035
}
10011036
}

src/nunit.analyzers/DiagnosticSuppressors/DereferencePossiblyNullReferenceSuppressor.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,12 @@ private static bool InvalidatedBy(string assignment, string possibleNullReferenc
407407

408408
private static bool CoveredBy(string assertedNotNull, string possibleNullReference)
409409
{
410+
int exclamation = assertedNotNull.IndexOf('!');
411+
if (exclamation >= 0)
412+
{
413+
assertedNotNull = assertedNotNull.Replace("!", string.Empty);
414+
}
415+
410416
if (possibleNullReference == assertedNotNull)
411417
{
412418
return true;

0 commit comments

Comments
 (0)