Beispiel #1
0
    public async Task DiagnosticsAreReturned_ForIncompleteActionResults()
    {
        // Arrange
        var source           = @"
using Microsoft.AspNetCore.Mvc;

namespace Test
{
    [ApiController]
    [Route(""[controller]/[action]"")
    public class TestController : ControllerBase
    {
        public IActionResult Get(int id)
        {
            if (id == 0)
            {
                return /*MM*/NotFound();
            }

            return;
        }
    }
}";
        var testSource       = TestSource.Read(source);
        var expectedLocation = testSource.DefaultMarkerLocation;

        // Act
        var result = await Executor.GetDiagnosticsAsync(testSource.Source);

        // Assert
        var diagnostic = Assert.Single(result, d => d.Id == ApiDiagnosticDescriptors.API1000_ActionReturnsUndocumentedStatusCode.Id);

        AnalyzerAssert.DiagnosticLocation(expectedLocation, diagnostic.Location);
    }
        public async Task StartupAnalyzer_MvcOptionsAnalysis_MultipleUseMvc()
        {
            // Arrange
            var source = ReadSource("MvcOptions_UseMvcMultiple");

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            var mvcOptionsAnalysis = Assert.Single(Analyses.OfType <MvcOptionsAnalysis>());

            Assert.Null(mvcOptionsAnalysis.EndpointRoutingEnabled);

            Assert.Collection(
                diagnostics,
                diagnostic =>
            {
                Assert.Same(StartupAnalzyer.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MM1"], diagnostic.Location);
            },
                diagnostic =>
            {
                Assert.Same(StartupAnalzyer.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MM2"], diagnostic.Location);
            },
                diagnostic =>
            {
                Assert.Same(StartupAnalzyer.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MM3"], diagnostic.Location);
            });
        }
        public async Task StartupAnalyzer_MvcOptionsAnalysis_MultipleMiddleware()
        {
            // Arrange
            var source = Read("MvcOptions_UseMvcWithOtherMiddleware");

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            var optionsAnalysis = Assert.Single(Analyses.OfType <OptionsAnalysis>());

            Assert.False(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis));

            var middlewareAnalysis = Assert.Single(Analyses.OfType <MiddlewareAnalysis>());

            Assert.Collection(
                middlewareAnalysis.Middleware,
                item => Assert.Equal("UseStaticFiles", item.UseMethod.Name),
                item => Assert.Equal("UseMiddleware", item.UseMethod.Name),
                item => Assert.Equal("UseMvc", item.UseMethod.Name),
                item => Assert.Equal("UseRouting", item.UseMethod.Name),
                item => Assert.Equal("UseEndpoints", item.UseMethod.Name));

            Assert.Collection(
                diagnostics,
                diagnostic =>
            {
                Assert.Same(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
            });
        }
        public async Task StartupAnalyzer_MvcOptionsAnalysis_MultipleUseMvc()
        {
            // Arrange
            var source = Read("MvcOptions_UseMvcMultiple");

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            var optionsAnalysis = Assert.Single(Analyses.OfType <OptionsAnalysis>());

            Assert.False(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis));

            Assert.Collection(
                diagnostics,
                diagnostic =>
            {
                Assert.Same(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MM1"], diagnostic.Location);
            },
                diagnostic =>
            {
                Assert.Same(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MM2"], diagnostic.Location);
            },
                diagnostic =>
            {
                Assert.Same(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MM3"], diagnostic.Location);
            });
        }
        public async Task TryGetActualResponseMetadata_ActionReturningNotFoundAndModel()
        {
            // Arrange
            var typeName   = typeof(TryGetActualResponseMetadataController).FullName;
            var methodName = nameof(TryGetActualResponseMetadataController.ActionReturningNotFoundAndModel);

            // Act
            var(success, responseMetadatas, testSource) = await TryGetActualResponseMetadata(typeName, methodName);

            // Assert
            Assert.True(success);
            Assert.Collection(
                responseMetadatas,
                metadata =>
            {
                Assert.False(metadata.IsDefaultResponse);
                Assert.Equal(204, metadata.StatusCode);
                AnalyzerAssert.DiagnosticLocation(testSource.MarkerLocations["MM1"], metadata.ReturnOperation.Syntax.GetLocation());
            },
                metadata =>
            {
                Assert.True(metadata.IsDefaultResponse);
                AnalyzerAssert.DiagnosticLocation(testSource.MarkerLocations["MM2"], metadata.ReturnOperation.Syntax.GetLocation());
            });
        }
        public async Task StartupAnalyzer_MvcOptionsAnalysis_FindsEndpointRoutingEnabled(string sourceFileName, string mvcMiddlewareName)
        {
            // Arrange
            var source = ReadSource(sourceFileName);

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            var mvcOptionsAnalysis = Assert.Single(Analyses.OfType <MvcOptionsAnalysis>());

            Assert.Null(mvcOptionsAnalysis.EndpointRoutingEnabled);

            var middlewareAnalysis = Assert.Single(Analyses.OfType <MiddlewareAnalysis>());
            var middleware         = Assert.Single(middlewareAnalysis.Middleware);

            Assert.Equal(mvcMiddlewareName, middleware.UseMethod.Name);

            Assert.Collection(
                diagnostics,
                diagnostic =>
            {
                Assert.Same(StartupAnalzyer.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
            });
        }
        public async Task InternalUsage_FindsUseOfInternalTypesInMethodBody()
        {
            // Arrange
            var source = Read("UsersRendererTypesInMethodBody");

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            Assert.Collection(
                diagnostics,
                diagnostic =>
            {
                Assert.Same(DiagnosticDescriptors.DoNotUseRenderTreeTypes, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MMField"], diagnostic.Location);
            },
                diagnostic =>
            {
                Assert.Same(DiagnosticDescriptors.DoNotUseRenderTreeTypes, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MMNewObject"], diagnostic.Location);
            },
                diagnostic =>
            {
                Assert.Same(DiagnosticDescriptors.DoNotUseRenderTreeTypes, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MMProperty"], diagnostic.Location);
            });
        }
        public async Task StartupAnalyzer_MvcOptionsAnalysis_MultipleMiddleware()
        {
            // Arrange
            var source = ReadSource("MvcOptions_UseMvcWithOtherMiddleware");

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            var mvcOptionsAnalysis = Assert.Single(Analyses.OfType <MvcOptionsAnalysis>());

            Assert.Null(mvcOptionsAnalysis.EndpointRoutingEnabled);

            var middlewareAnalysis = Assert.Single(Analyses.OfType <MiddlewareAnalysis>());

            Assert.Collection(
                middlewareAnalysis.Middleware,
                item => Assert.Equal("UseAuthorization", item.UseMethod.Name),
                item => Assert.Equal("UseMiddleware", item.UseMethod.Name),
                item => Assert.Equal("UseMvc", item.UseMethod.Name),
                item => Assert.Equal("UseRouting", item.UseMethod.Name),
                item => Assert.Equal("UseEndpoints", item.UseMethod.Name));

            Assert.Collection(
                diagnostics,
                diagnostic =>
            {
                Assert.Same(StartupAnalzyer.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
            });
        }
Beispiel #9
0
        public async Task StartupAnalyzer_WorksWithOtherMethodsInProgram()
        {
            // Arrange
            var source = TestSource.Read(@"using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        builder.Services.AddMvc();
        var app = builder.Build();
        app.UseStaticFiles();
        app.UseMiddleware<AuthorizationMiddleware>();
        /*MM*/app.UseMvc();
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
        });
        app.Run();
    }

    private static void MethodA()
    {
    }

    private static void MethodB()
    {
    }
}");

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            var optionsAnalysis = Assert.Single(Analyses.OfType <OptionsAnalysis>());

            Assert.False(OptionsFacts.IsEndpointRoutingExplicitlyDisabled(optionsAnalysis));

            var middlewareAnalysis = Assert.Single(Analyses.OfType <MiddlewareAnalysis>());

            Assert.Collection(
                middlewareAnalysis.Middleware,
                item => Assert.Equal("UseStaticFiles", item.UseMethod.Name),
                item => Assert.Equal("UseMiddleware", item.UseMethod.Name),
                item => Assert.Equal("UseMvc", item.UseMethod.Name),
                item => Assert.Equal("UseRouting", item.UseMethod.Name),
                item => Assert.Equal("UseEndpoints", item.UseMethod.Name));

            Assert.Collection(
                diagnostics,
                diagnostic =>
            {
                Assert.Same(StartupAnalyzer.Diagnostics.UnsupportedUseMvcWithEndpointRouting, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
                Assert.Contains("inside 'Main", diagnostic.GetMessage());
            });
        }
Beispiel #10
0
        public async Task PublicExposureOfPubternalTypeProducesInTypeDefinitionPUB0001(string member)
        {
            var code       = GetSourceFromNamespaceDeclaration($@"
namespace A
{{
    {member}
}}");
            var diagnostic = Assert.Single(await GetDiagnostics(code.Source));

            Assert.Equal("PUB0001", diagnostic.Id);
            AnalyzerAssert.DiagnosticLocation(code.DefaultMarkerLocation, diagnostic.Location);
        }
 private void AssertDiagnostic(DiagnosticLocation expectedLocation, Diagnostic[] actualDiagnostics)
 {
     // Assert
     Assert.Collection(
         actualDiagnostics,
         diagnostic =>
     {
         Assert.Equal(DiagnosticDescriptor.Id, diagnostic.Id);
         Assert.Same(DiagnosticDescriptor, diagnostic.Descriptor);
         AnalyzerAssert.DiagnosticLocation(expectedLocation, diagnostic.Location);
     });
 }
        public async Task InternalUsage_FindsUseOfRenderTreeType()
        {
            // Arrange
            var source = Read("UsesRenderTreeFrameTypeAsLocal");

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            Assert.Collection(
                diagnostics,
                diagnostic =>
            {
                Assert.Same(DiagnosticDescriptors.DoNotUseRenderTreeTypes, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
            });
        }
Beispiel #13
0
        public async Task DefinitionOfPubternalCrossAssemblyProducesPUB0002(string member)
        {
            var code = TestSource.Read($@"
using A.Internal.Namespace;
namespace A
{{
    internal class T
    {{
        {member}
    }}
}}");

            var diagnostic = Assert.Single(await GetDiagnosticWithProjectReference(code.Source));

            Assert.Equal("PUB0002", diagnostic.Id);
            AnalyzerAssert.DiagnosticLocation(code.DefaultMarkerLocation, diagnostic.Location);
        }
        private async Task VerifyDefault(TestSource testSource)
        {
            // Arrange
            var expectedLocation = testSource.DefaultMarkerLocation;

            // Act
            var result = await Executor.GetDiagnosticsAsync(testSource.Source);

            // Assert
            Assert.Collection(
                result,
                diagnostic =>
            {
                Assert.Equal(DiagnosticDescriptor.Id, diagnostic.Id);
                Assert.Same(DiagnosticDescriptor, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(expectedLocation, diagnostic.Location);
            });
        }
        public async Task StartupAnalyzer_UseAuthorizationConfiguredAfterUseEndpoints_ReportsDiagnostics()
        {
            // Arrange
            var source = Read(nameof(TestFiles.StartupAnalyzerTest.UseAuthAfterUseEndpoints));

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            var middlewareAnalysis = Assert.Single(Analyses.OfType <MiddlewareAnalysis>());

            Assert.NotEmpty(middlewareAnalysis.Middleware);
            Assert.Collection(diagnostics,
                              diagnostic =>
            {
                Assert.Same(StartupAnalyzer.Diagnostics.IncorrectlyConfiguredAuthorizationMiddleware, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
            });
        }
Beispiel #16
0
        private async Task VerifyDefault(DiagnosticDescriptor descriptor, [CallerMemberName] string testMethod = "")
        {
            // Arrange
            var testSource       = MvcTestSource.Read(GetType().Name, testMethod);
            var expectedLocation = testSource.DefaultMarkerLocation;

            // Act
            var result = await Executor.GetDiagnosticsAsync(testSource.Source);

            // Assert
            Assert.Collection(
                result,
                diagnostic =>
            {
                Assert.Equal(descriptor.Id, diagnostic.Id);
                Assert.Same(descriptor, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(expectedLocation, diagnostic.Location);
            });
        }
        public async Task StartupAnalyzer_ServicesAnalysis_CallBuildServiceProvider()
        {
            // Arrange
            var source = Read("ConfigureServices_BuildServiceProvider");

            // Act
            var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

            // Assert
            var servicesAnalysis = Assert.Single(Analyses.OfType <ServicesAnalysis>());

            Assert.NotEmpty(servicesAnalysis.Services);
            Assert.Collection(diagnostics,
                              diagnostic =>
            {
                Assert.Same(StartupAnalyzer.Diagnostics.BuildServiceProviderShouldNotCalledInConfigureServicesMethod, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MM1"], diagnostic.Location);
            });
        }
    public async Task InternalUsage_FindsUseOfInternalTypesInDeclarations()
    {
        // Arrange
        var source = Read("UsesRendererTypesInDeclarations");

        // Act
        var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);

        // Assert
        Assert.Collection(
            diagnostics,
            diagnostic =>
        {
            Assert.Same(DiagnosticDescriptors.DoNotUseRenderTreeTypes, diagnostic.Descriptor);
            AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MMBaseClass"], diagnostic.Location);
        },
            diagnostic =>
        {
            Assert.Same(DiagnosticDescriptors.DoNotUseRenderTreeTypes, diagnostic.Descriptor);
            AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MMField"], diagnostic.Location);
        },
            diagnostic =>
        {
            Assert.Same(DiagnosticDescriptors.DoNotUseRenderTreeTypes, diagnostic.Descriptor);
            AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MMInvocation"], diagnostic.Location);
        },
            diagnostic =>
        {
            Assert.Same(DiagnosticDescriptors.DoNotUseRenderTreeTypes, diagnostic.Descriptor);
            AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MMProperty"], diagnostic.Location);
        },
            diagnostic =>
        {
            Assert.Same(DiagnosticDescriptors.DoNotUseRenderTreeTypes, diagnostic.Descriptor);
            AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MMParameter"], diagnostic.Location);
        },
            diagnostic =>
        {
            Assert.Same(DiagnosticDescriptors.DoNotUseRenderTreeTypes, diagnostic.Descriptor);
            AnalyzerAssert.DiagnosticLocation(source.MarkerLocations["MMReturnType"], diagnostic.Location);
        });
    }
    private async Task RunTest([CallerMemberName] string testMethod = "")
    {
        // Arrange
        var descriptor       = ApiDiagnosticDescriptors.API1003_ApiActionsDoNotRequireExplicitModelValidationCheck;
        var testSource       = MvcTestSource.Read(GetType().Name, testMethod);
        var expectedLocation = testSource.DefaultMarkerLocation;

        // Act
        var result = await AnalyzerRunner.GetDiagnosticsAsync(testSource.Source);

        // Assert
        Assert.Collection(
            result,
            diagnostic =>
        {
            Assert.Equal(descriptor.Id, diagnostic.Id);
            Assert.Same(descriptor, diagnostic.Descriptor);
            AnalyzerAssert.DiagnosticLocation(expectedLocation, diagnostic.Location);
        });
    }
Beispiel #20
0
    private async Task RunTest(DiagnosticDescriptor descriptor, object[] args, [CallerMemberName] string testMethod = "")
    {
        // Arrange
        var testSource       = MvcTestSource.Read(GetType().Name, testMethod);
        var expectedLocation = testSource.DefaultMarkerLocation;

        // Act
        var result = await Executor.GetDiagnosticsAsync(testSource.Source);

        // Assert
        Assert.Collection(
            result,
            diagnostic =>
        {
            Assert.Equal(descriptor.Id, diagnostic.Id);
            Assert.Same(descriptor, diagnostic.Descriptor);
            AnalyzerAssert.DiagnosticLocation(expectedLocation, diagnostic.Location);
            Assert.Equal(string.Format(CultureInfo.InvariantCulture, descriptor.MessageFormat.ToString(CultureInfo.InvariantCulture), args), diagnostic.GetMessage(CultureInfo.InvariantCulture));
        });
    }
Beispiel #21
0
        private async Task RunTest(string typeName, string parameterName, [CallerMemberName] string testMethod = "")
        {
            // Arrange
            var descriptor       = DiagnosticDescriptors.MVC1004_ParameterNameCollidesWithTopLevelProperty;
            var testSource       = MvcTestSource.Read(GetType().Name, testMethod);
            var expectedLocation = testSource.DefaultMarkerLocation;

            // Act
            var result = await Runner.GetDiagnosticsAsync(testSource.Source);

            // Assert
            Assert.Collection(
                result,
                diagnostic =>
            {
                Assert.Equal(descriptor.Id, diagnostic.Id);
                Assert.Same(descriptor, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(expectedLocation, diagnostic.Location);
                Assert.Equal(string.Format(descriptor.MessageFormat.ToString(), typeName, parameterName), diagnostic.GetMessage());
            });
        }
        private async Task VerifyDefault(TestSource testSource)
        {
            // Arrange
            var expectedLocation = testSource.DefaultMarkerLocation;

            // Act
            var result = await Executor.GetDiagnosticsAsync(testSource.Source);

            // Assert
            // We want to ignore C# diagnostics because they'll include diagnostics for not awaiting bits correctly. The purpose of this analyzer is to
            // improve on those error messages but not remove them.
            var filteredDiagnostics = result.Where(diagnostic => diagnostic.Id.StartsWith("MVC"));

            Assert.Collection(
                filteredDiagnostics,
                diagnostic =>
            {
                Assert.Equal(DiagnosticDescriptor.Id, diagnostic.Id);
                Assert.Same(DiagnosticDescriptor, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(expectedLocation, diagnostic.Location);
            });
        }
Beispiel #23
0
        private async Task RunTestFor1006(int statusCode, [CallerMemberName] string testMethod = "")
        {
            // Arrange
            var descriptor       = DiagnosticDescriptors.MVC1006_ActionDoesNotReturnDocumentedStatusCode;
            var testSource       = MvcTestSource.Read(GetType().Name, testMethod);
            var expectedLocation = testSource.DefaultMarkerLocation;
            var executor         = new ApiCoventionWith1006DiagnosticEnabledRunner();

            // Act
            var result = await executor.GetDiagnosticsAsync(testSource.Source);

            // Assert
            Assert.Collection(
                result,
                diagnostic =>
            {
                Assert.Equal(descriptor.Id, diagnostic.Id);
                Assert.Same(descriptor, diagnostic.Descriptor);
                AnalyzerAssert.DiagnosticLocation(expectedLocation, diagnostic.Location);
                Assert.Equal(string.Format(descriptor.MessageFormat.ToString(), new[] { statusCode.ToString() }), diagnostic.GetMessage());
            });
        }