private Task <Compilation> GetCompilation(string test)
        {
            var testSource = MvcTestSource.Read(GetType().Name, test);
            var project    = DiagnosticProject.Create(GetType().Assembly, new[] { testSource.Source });

            return(project.GetCompilationAsync());
        }
        private Task <Compilation> GetCompilationAsync(string test = "SymbolApiConventionMatcherTestFile")
        {
            var testSource = MvcTestSource.Read(GetType().Name, test);
            var project    = DiagnosticProject.Create(GetType().Assembly, new[] { testSource.Source });

            return(project.GetCompilationAsync());
        }
        public async Task IsApiControllerAction_ReturnsFalse_IfMethodReturnTypeIsInvalid()
        {
            // Arrange
            var source      = @"
using Microsoft.AspNetCore.Mvc;

namespace TestNamespace
{
    [ApiController]
    public class TestController : ControllerBase
    {
        public DoesNotExist Get(int id)
        {
            if (id == 0)
            {
                return NotFound();
            }

            return new DoesNotExist(id);
        }
    }
}";
            var project     = DiagnosticProject.Create(GetType().Assembly, new[] { source });
            var compilation = await project.GetCompilationAsync();

            var symbolCache = new ApiControllerSymbolCache(compilation);
            var method      = (IMethodSymbol)compilation.GetTypeByMetadataName("TestNamespace.TestController").GetMembers("Get").First();

            // Act
            var result = ApiControllerFacts.IsApiControllerAction(symbolCache, method);

            // Assert
            Assert.False(result);
        }
        private Task <Compilation> GetCompilation()
        {
            var testSource = MvcTestSource.Read(GetType().Name, "ApiConventionAnalyzerTestFile");
            var project    = DiagnosticProject.Create(GetType().Assembly, new[] { testSource.Source });

            return(project.GetCompilationAsync());
        }
Beispiel #5
0
        private async Task <Compilation> GetCompilationForGetName()
        {
            var testSource = MvcTestSource.Read(GetType().Name, "GetNameTests");
            var project    = DiagnosticProject.Create(GetType().Assembly, new[] { testSource.Source });

            var compilation = await project.GetCompilationAsync();

            return(compilation);
        }
Beispiel #6
0
    /// <summary>
    /// Given classes in the form of strings, and an DiagnosticAnalyzer to apply to it, return the diagnostics found in the string after converting it to a document.
    /// </summary>
    /// <param name="sources">Classes in the form of strings</param>
    /// <param name="analyzer">The analyzer to be run on the sources</param>
    /// <param name="additionalEnabledDiagnostics">Additional diagnostics to enable at Info level</param>
    /// <param name="getAllDiagnostics">
    /// When <c>true</c>, returns all diagnostics including compilation errors.
    /// Otherwise; only returns analyzer diagnostics.
    /// </param>
    /// <returns>An IEnumerable of Diagnostics that surfaced in the source code, sorted by Location</returns>
    protected Task <Diagnostic[]> GetDiagnosticsAsync(
        string[] sources,
        DiagnosticAnalyzer analyzer,
        string[] additionalEnabledDiagnostics,
        bool getAllDiagnostics = true)
    {
        var project = DiagnosticProject.Create(GetType().Assembly, sources);

        return(GetDiagnosticsAsync(new[] { project }, analyzer, additionalEnabledDiagnostics));
    }
Beispiel #7
0
        public Project CreateProject(string source)
        {
            if (!source.EndsWith(".cs", StringComparison.Ordinal))
            {
                source += ".cs";
            }

            var read = Read(source);

            return(DiagnosticProject.Create(GetType().Assembly, new[] { read.Source, }));
        }
Beispiel #8
0
        public Project CreateProject(string source)
        {
            if (!source.EndsWith(".cs"))
            {
                source = source + ".cs";
            }

            var read = Read(source);

            return(DiagnosticProject.Create(GetType().Assembly, new[] { read.Source, }));
        }
Beispiel #9
0
        private async Task <bool> IsProblematicParameterTest([CallerMemberName] string testMethod = "")
        {
            var testSource = MvcTestSource.Read(GetType().Name, testMethod);
            var project    = DiagnosticProject.Create(GetType().Assembly, new[] { testSource.Source });

            var compilation = await project.GetCompilationAsync();

            var modelType = compilation.GetTypeByMetadataName($"Microsoft.AspNetCore.Mvc.Analyzers.TopLevelParameterNameAnalyzerTestFiles.{testMethod}");
            var method    = (IMethodSymbol)modelType.GetMembers("ActionMethod").First();
            var parameter = method.Parameters[0];

            Assert.True(TopLevelParameterNameAnalyzer.SymbolCache.TryCreate(compilation, out var symbolCache));

            var result = TopLevelParameterNameAnalyzer.IsProblematicParameter(symbolCache, parameter);

            return(result);
        }
        public static Project CreateProjectWithReferencesInBinDir(Assembly testAssembly, params string[] source)
        {
            // The deps file in the project is incorrect and does not contain "compile" nodes for some references.
            // However these binaries are always present in the bin output. As a "temporary" workaround, we'll add
            // every dll file that's present in the test's build output as a metadatareference.

            var project = DiagnosticProject.Create(testAssembly, source);

            foreach (var assembly in Directory.EnumerateFiles(AppContext.BaseDirectory, "*.dll"))
            {
                if (!project.MetadataReferences.Any(c => string.Equals(Path.GetFileNameWithoutExtension(c.Display), Path.GetFileNameWithoutExtension(assembly), StringComparison.OrdinalIgnoreCase)))
                {
                    project = project.AddMetadataReference(MetadataReference.CreateFromFile(assembly));
                }
            }

            return(project);
        }
Beispiel #11
0
        public async Task SpecifiesModelType_ReturnsTrue_IfModelBinderSpecifiesTypeFromProperty()
        {
            var testMethod = nameof(SpecifiesModelType_ReturnsTrue_IfModelBinderSpecifiesTypeFromProperty);
            var testSource = MvcTestSource.Read(GetType().Name, "SpecifiesModelTypeTests");
            var project    = DiagnosticProject.Create(GetType().Assembly, new[] { testSource.Source });

            var compilation = await project.GetCompilationAsync();

            Assert.True(TopLevelParameterNameAnalyzer.SymbolCache.TryCreate(compilation, out var symbolCache));

            var type   = compilation.GetTypeByMetadataName(typeof(SpecifiesModelTypeTests).FullName);
            var method = (IMethodSymbol)type.GetMembers(testMethod).First();

            var parameter = method.Parameters[0];
            var result    = TopLevelParameterNameAnalyzer.SpecifiesModelType(symbolCache, parameter);

            Assert.True(result);
        }
        private async Task <(bool result, IList <ActualApiResponseMetadata> responseMetadatas, TestSource testSource)> TryGetActualResponseMetadata(string typeName, string methodName)
        {
            var testSource = MvcTestSource.Read(GetType().Name, "TryGetActualResponseMetadataTests");
            var project    = DiagnosticProject.Create(GetType().Assembly, new[] { testSource.Source });

            var compilation = await GetCompilation("TryGetActualResponseMetadataTests");

            var type        = compilation.GetTypeByMetadataName(typeName);
            var method      = (IMethodSymbol)type.GetMembers(methodName).First();
            var symbolCache = new ApiControllerSymbolCache(compilation);

            var syntaxTree    = method.DeclaringSyntaxReferences[0].SyntaxTree;
            var methodSyntax  = (MethodDeclarationSyntax)syntaxTree.GetRoot().FindNode(method.Locations[0].SourceSpan);
            var semanticModel = compilation.GetSemanticModel(syntaxTree);

            var result = ActualApiResponseMetadataFactory.TryGetActualResponseMetadata(symbolCache, semanticModel, methodSyntax, CancellationToken.None, out var responseMetadatas);

            return(result, responseMetadatas, testSource);
        }
        private async Task <ActualApiResponseMetadata?> RunInspectReturnStatementSyntax(string source, string test)
        {
            var project     = DiagnosticProject.Create(GetType().Assembly, new[] { source });
            var compilation = await project.GetCompilationAsync();

            var symbolCache = new ApiControllerSymbolCache(compilation);

            var returnType = compilation.GetTypeByMetadataName($"{Namespace}.{test}");
            var syntaxTree = returnType.DeclaringSyntaxReferences[0].SyntaxTree;

            var method          = (IMethodSymbol)returnType.GetMembers().First();
            var methodSyntax    = syntaxTree.GetRoot().FindNode(method.Locations[0].SourceSpan);
            var returnStatement = methodSyntax.DescendantNodes().OfType <ReturnStatementSyntax>().First();

            return(SymbolApiResponseMetadataProvider.InspectReturnStatementSyntax(
                       symbolCache,
                       compilation.GetSemanticModel(syntaxTree),
                       returnStatement,
                       CancellationToken.None));
        }
Beispiel #14
0
        public async Task IsProblematicParameter_ReturnsFalse_ForSimpleTypes()
        {
            var testName   = nameof(IsProblematicParameter_ReturnsFalse_ForSimpleTypes);
            var testSource = MvcTestSource.Read(GetType().Name, testName);
            var project    = DiagnosticProject.Create(GetType().Assembly, new[] { testSource.Source });

            var compilation = await project.GetCompilationAsync();

            var modelType = compilation.GetTypeByMetadataName($"Microsoft.AspNetCore.Mvc.Analyzers.TopLevelParameterNameAnalyzerTestFiles.{testName}");
            var method    = (IMethodSymbol)modelType.GetMembers("ActionMethod").First();

            Assert.True(TopLevelParameterNameAnalyzer.SymbolCache.TryCreate(compilation, out var symbolCache));

            Assert.Collection(
                method.Parameters,
                p => Assert.False(TopLevelParameterNameAnalyzer.IsProblematicParameter(symbolCache, p)),
                p => Assert.False(TopLevelParameterNameAnalyzer.IsProblematicParameter(symbolCache, p)),
                p => Assert.False(TopLevelParameterNameAnalyzer.IsProblematicParameter(symbolCache, p)),
                p => Assert.False(TopLevelParameterNameAnalyzer.IsProblematicParameter(symbolCache, p)),
                p => Assert.False(TopLevelParameterNameAnalyzer.IsProblematicParameter(symbolCache, p)));
        }
        public async Task InspectReturnExpression_ReturnsNull_IfReturnExpressionCannotBeFound()
        {
            // Arrange & Act
            var source      = @"
            using Microsoft.AspNetCore.Mvc;

namespace Microsoft.AspNetCore.Mvc.Api.Analyzers
{
    [ApiController]
    public class TestController : ControllerBase
    {
        public IActionResult Get(int id)
        {
            return new DoesNotExist(id);
        }
    }
}";
            var project     = DiagnosticProject.Create(GetType().Assembly, new[] { source });
            var compilation = await project.GetCompilationAsync();

            var symbolCache = new ApiControllerSymbolCache(compilation);

            var returnType = compilation.GetTypeByMetadataName($"{Namespace}.TestController");
            var syntaxTree = returnType.DeclaringSyntaxReferences[0].SyntaxTree;

            var method          = (IMethodSymbol)returnType.GetMembers().First();
            var methodSyntax    = syntaxTree.GetRoot().FindNode(method.Locations[0].SourceSpan);
            var returnStatement = methodSyntax.DescendantNodes().OfType <ReturnStatementSyntax>().First();

            var actualResponseMetadata = ActualApiResponseMetadataFactory.InspectReturnStatementSyntax(
                symbolCache,
                compilation.GetSemanticModel(syntaxTree),
                returnStatement,
                CancellationToken.None);

            // Assert
            Assert.Null(actualResponseMetadata);
        }
        private Project GetProject(string testMethod)
        {
            var testSource = Read(testMethod + ".Input");

            return(DiagnosticProject.Create(GetType().Assembly, new[] { testSource }));
        }