Skip to content

Commit

Permalink
Remove rule for docs and add rule for method length (#179)
Browse files Browse the repository at this point in the history
* Remove rule for docs and add rule for method length

* change error message

* fixes

* move to constant

* fix test

* add extra test for xunit and fleunt assertion and make them work

* fixes from code reivew

* add override from config
  • Loading branch information
joeldickson authored Aug 14, 2023
1 parent c7cf07f commit 7e7ce5e
Show file tree
Hide file tree
Showing 15 changed files with 289 additions and 191 deletions.
17 changes: 17 additions & 0 deletions src/Agoda.Analyzers.Test/Agoda.Analyzers.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,18 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<None Remove="System.Xml.ReaderWriter.dll" />
<None Remove="System.Xml.XDocument.dll" />
</ItemGroup>
<ItemGroup>
<Content Include="System.Xml.ReaderWriter.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="System.Xml.XDocument.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Agoda.Analyzers.CodeFixes\Agoda.Analyzers.CodeFixes.csproj" />
<ProjectReference Include="..\Agoda.Analyzers\Agoda.Analyzers.csproj" />
Expand All @@ -35,6 +47,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="5.6.0" />
<PackageReference Include="Microsoft.AspNet.Mvc" Version="5.2.3" />
<PackageReference Include="Microsoft.AspNet.Razor" Version="3.2.3" />
<PackageReference Include="Microsoft.AspNet.WebPages" Version="3.2.3" />
Expand Down Expand Up @@ -72,6 +85,10 @@
<PackageReference Include="System.Runtime.Extensions" Version="4.3.1" />
<PackageReference Include="System.Threading" Version="4.3.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.1" />
<PackageReference Include="System.Xml.XDocument" Version="4.3.0" />
<PackageReference Include="xunit" Version="2.5.0" />
<PackageReference Include="xunit.assert" Version="2.5.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Web" />
Expand Down
62 changes: 60 additions & 2 deletions src/Agoda.Analyzers.Test/AgodaCustom/AG0012UnitTests.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
using Agoda.Analyzers.AgodaCustom;
using System.Reflection;
using Agoda.Analyzers.AgodaCustom;
using Agoda.Analyzers.Test.Helpers;
using Microsoft.CodeAnalysis.Diagnostics;
using NUnit.Framework;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using FluentAssertions;

namespace Agoda.Analyzers.Test.AgodaCustom;

Expand Down Expand Up @@ -87,12 +91,66 @@ public void This_Is_Valid()
}
}"
};

await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
}

[Test]
public async Task AG0012_WithXUnitAssertion_ShouldNotShowWarning()
{
var code = new CodeDescriptor
{
References = new[] { typeof(Xunit.FactAttribute).Assembly, typeof(Xunit.Assert).Assembly },
Code = @"
using Xunit;
namespace Tests
{
public class TestClass
{
[Fact]
public void This_Is_Valid()
{
int[] arrayToAssert = { 1, 2, 3 };
Assert.NotNull(arrayToAssert);
}
}
}"
};

await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
}

[Test]
public async Task AG0012_WithFluentAssertions_ShouldNotShowWarning()
{
var code = new CodeDescriptor
{
References = new[] { typeof(NUnitAttribute).Assembly,
typeof(FluentAssertions.TypeExtensions).Assembly,
typeof(XDocument).Assembly,
typeof(XmlNode).Assembly,
Assembly.LoadFrom("System.Xml.XDocument.dll"),
Assembly.LoadFrom("System.Xml.ReaderWriter.dll"),
},
Code = @"
using NUnit.Framework;
using FluentAssertions;
namespace Tests
{
internal class TestClass
{
[Test]
internal void This_Is_Valid()
{
int arrayToAssert = 1;
arrayToAssert.Should().Be(1);
}
}
}"
};
await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
}
[Test]
public async Task AG0012_WithShouldlyAssertion_ShouldNotShowWarning()
{
Expand Down
124 changes: 34 additions & 90 deletions src/Agoda.Analyzers.Test/AgodaCustom/AG0039UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,107 +8,51 @@ namespace Agoda.Analyzers.Test.AgodaCustom;

class AG0039UnitTests : DiagnosticVerifier
{
protected override DiagnosticAnalyzer DiagnosticAnalyzer => new AG0039UndocumentedMemberAnalyzer();

protected override string DiagnosticId => AG0039UndocumentedMemberAnalyzer.DIAGNOSTIC_ID;
protected override DiagnosticAnalyzer DiagnosticAnalyzer => new AG0039MethodLineLengthAnalyzer();

protected override string DiagnosticId => AG0039MethodLineLengthAnalyzer.DIAGNOSTIC_ID;

[Test]
[TestCase(@"
/// <summary>
///
/// </summary>
public class NotDoc
{
/// <summary>
///
/// </summary>
public string str1 { get; }
///// <summary>
/////
///// </summary>
//public const int int2 = 1;
///// <summary>
/////
///// </summary>
//public void DoesNothing() { }
///// <summary>
/////
///// </summary>
//public event SampleEventHandler SampleEvent;
///// <summary>
/////
///// </summary>
///// <param name=""sender""></param>
//public delegate void SampleEventHandler(object sender);
}
")]
[TestCase(@"
/// <include file='xml_include_tag.xml' path='MyDocs/MyMembers[@name=""test""]/*' />
public class NotDoc
public async Task AG0039_At40LinesOfCode_ShowWarning()
{
var code = @"
internal class InternalClass
{
/// <include file='xml_include_tag.xml' path='MyDocs/MyMembers[@name=""test""]/*' />
public string str1 { get; }
/// <include file='xml_include_tag.xml' path='MyDocs/MyMembers[@name=""test""]/*' />
public const int int2 = 1;
/// <include file='xml_include_tag.xml' path='MyDocs/MyMembers[@name=""test""]/*' />
public void DoesNothing() { }
/// <include file='xml_include_tag.xml' path='MyDocs/MyMembers[@name=""test""]/*' />
public event SampleEventHandler SampleEvent;
/// <include file='xml_include_tag.xml' path='MyDocs/MyMembers[@name=""test""]/*' />
public delegate void SampleEventHandler(object sender);
private void MyMethod()
{
var a = 1;
";
for (int i = 0; i <= 121; i++)
{
code += "a += 1;\n";
}
code += @"
}
}
")]
public async Task AG0039_WithDoc_ShowNoWarning(string code)
{
await VerifyDiagnosticsAsync(code, EmptyDiagnosticResults);
";
await VerifyDiagnosticsAsync(code, new[]{
new DiagnosticLocation(4, 34, "MyMethod","126", "40"),
});
}

[Test]
[TestCase(@"
public class NotDoc
{
public string str1 {get;}
public const int int2 = 1;
public void DoesNothing() {}
public event SampleEventHandler SampleEvent;
public delegate void SampleEventHandler(object sender);
internal string internalString;
internal string internalStringProp {get;}
protected string protectedString;
private int _privateInt;
}
public async Task AG0039_At40LinesOfWhiteSpace_DoNotShowWarning()
{
var code = @"
internal class InternalClass
{
public string str1 {get;}
public const int int2 = 1;
public void DoesNothing() {}
public event SampleEventHandler SampleEvent;
public delegate void SampleEventHandler(object sender);
internal string internalString;
internal string internalStringProp {get;}
protected string protectedString;
private int _privateInt;
private class MyClass
private void MyMethod()
{
var a = 1;
";
for (int i = 0; i <= 121; i++)
{
code += "\n";
}
code += @"
}
}
")]
public async Task AG0039_WithoutDoc_ShowWarning(string code)
{

await VerifyDiagnosticsAsync(code, new[]{
new DiagnosticLocation(2, 18),
new DiagnosticLocation(4, 20),
new DiagnosticLocation(5, 23),
new DiagnosticLocation(6, 33),
new DiagnosticLocation(7, 53),
new DiagnosticLocation(8, 42),
new DiagnosticLocation(16, 35),
new DiagnosticLocation(17, 38),
new DiagnosticLocation(18, 33),
new DiagnosticLocation(19, 53),
new DiagnosticLocation(20, 42)
});
";
await VerifyDiagnosticsAsync(code,EmptyDiagnosticResults);
}
}
9 changes: 8 additions & 1 deletion src/Agoda.Analyzers.Test/Helpers/DiagnosticLocation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@ public class DiagnosticLocation
{
public int Line { get; }
public int Col { get; }

public string[] Args { get; set; }
public DiagnosticLocation(int line, int col, params string[] args)
{
Line = line;
Col = col;
Args = args;
}
public DiagnosticLocation(int line, int col)
{
if (line <= 0 || col <= 0)
Expand All @@ -15,5 +21,6 @@ public DiagnosticLocation(int line, int col)
}
Line = line;
Col = col;
Args = Array.Empty<string>();
}
}
2 changes: 1 addition & 1 deletion src/Agoda.Analyzers.Test/Helpers/DiagnosticVerifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ protected async Task VerifyDiagnosticsAsync(CodeDescriptor descriptor, Diagnosti
protected async Task VerifyDiagnosticsAsync(CodeDescriptor descriptor, DiagnosticLocation[] expectedLocations)
{
var baseResult = CSharpDiagnostic(DiagnosticId);
var expected = expectedLocations.Select(l => baseResult.WithLocation(l.Line, l.Col)).ToArray();
var expected = expectedLocations.Select(l => baseResult.WithLocation(l.Line, l.Col).WithArguments(l.Args)).ToArray();


var doc = CreateProject(new[] {descriptor.Code})
Expand Down
Binary file not shown.
Binary file not shown.
3 changes: 0 additions & 3 deletions src/Agoda.Analyzers/Agoda.Analyzers.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,6 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="RuleContent\AG0039UndocumentedMemberAnalyzer.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="RuleContent\AG0001DependencyResolverMustNotBeUsed.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using System.Linq;
using System.Net;

namespace Agoda.Analyzers.AgodaCustom
{
Expand Down Expand Up @@ -43,6 +44,7 @@ private static readonly LocalizableString Description
{
new AssertLibraryInfo("NUnit.Framework", "nunit.framework.dll", "Assert"),
new AssertLibraryInfo("Shouldly", "Shouldly.dll", "Should", "Shouldly.Should"),
//FluentAssertions
};

public override void Initialize(AnalysisContext context)
Expand Down Expand Up @@ -84,20 +86,27 @@ private static bool HasInvokedAssertStaticMethod(MethodDeclarationSyntax methodD

private static bool HasInvokedAssertExtensionMethod(MethodDeclarationSyntax methodDeclaration, SyntaxNodeAnalysisContext context)
{
return methodDeclaration.Body.Statements
var i = methodDeclaration.Body.Statements
.SelectMany(s => s.DescendantNodesAndSelf())
.OfType<InvocationExpressionSyntax>()
.Select(ies => ies.Expression)
.OfType<MemberAccessExpressionSyntax>()
.Select(mae => mae.Name)
.OfType<IdentifierNameSyntax>()
.Select(ins => context.SemanticModel.GetSymbolInfo(ins).Symbol)
.Any(symbol => AssertionLibraryList
.OfType<MemberAccessExpressionSyntax>();
var z = i.Select(mae => mae.Name)
.OfType<IdentifierNameSyntax>();
foreach (var identifierNameSyntax in z)
{
var t = context.SemanticModel.GetSymbolInfo(identifierNameSyntax);
var u = context.SemanticModel.GetDiagnostics();
var r = context.SemanticModel.GetDeclaredSymbol(identifierNameSyntax);
}
var y = z.Select(ins => context.SemanticModel.GetSymbolInfo(ins).Symbol)
.Any(symbol => AssertionLibraryList
.Where(lib => lib.HasExtenstionMethods).Any(lib
=> symbol.ContainingNamespace.ToDisplayString() == lib.Namespace
&& symbol.ContainingModule.ToDisplayString() == lib.Module
&& symbol.ContainingType.ToDisplayString().StartsWith(lib.Type)
&& symbol.Name.StartsWith(lib.Name)));
return y;
}

private class AssertLibraryInfo
Expand Down
Loading

0 comments on commit 7e7ce5e

Please sign in to comment.