private async Task VerifyAgainstBaselineUsingFile(string filename, string testSourceCode)
        {
            string[] expectedLines = await File.ReadAllLinesAsync(Path.Combine("Baselines", filename)).ConfigureAwait(false);

            var(d, r) = await RoslynTestUtils.RunGenerator(
                new LoggerMessageGenerator(),
                new[] { typeof(ILogger).Assembly, typeof(LoggerMessageAttribute).Assembly },
                new[] { testSourceCode }).ConfigureAwait(false);

            Assert.Empty(d);
            Assert.Single(r);

            Assert.True(CompareLines(expectedLines, r[0].SourceText,
                                     out string errorMessage), errorMessage);
        }
        internal void MultipleTypeDefinitions()
        {
            // Adding a dependency to an assembly that has internal definitions of public types
            // should not result in a collision and break generation.
            // Verify usage of the extension GetBestTypeByMetadataName(this Compilation) instead of Compilation.GetTypeByMetadataName().
            var referencedSource = @"
                namespace Microsoft.Extensions.Logging
                {
                    internal class LoggerMessageAttribute { }
                }
                namespace Microsoft.Extensions.Logging
                {
                    internal interface ILogger { }
                    internal enum LogLevel { }
                }";

            // Compile the referenced assembly first.
            Compilation referencedCompilation = CompilationHelper.CreateCompilation(referencedSource);

            // Obtain the image of the referenced assembly.
            byte[] referencedImage = CompilationHelper.CreateAssemblyImage(referencedCompilation);

            // Generate the code
            string source = @"
                namespace Test
                {
                    using Microsoft.Extensions.Logging;

                    partial class C
                    {
                        [LoggerMessage(EventId = 1, Level = LogLevel.Debug, Message = ""M1"")]
                        static partial void M1(ILogger logger);
                    }
                }";

            MetadataReference[]    additionalReferences = { MetadataReference.CreateFromImage(referencedImage) };
            Compilation            compilation          = CompilationHelper.CreateCompilation(source, additionalReferences);
            LoggerMessageGenerator generator            = new LoggerMessageGenerator();

            (ImmutableArray <Diagnostic> diagnostics, ImmutableArray <GeneratedSourceResult> generatedSources) =
                RoslynTestUtils.RunGenerator(compilation, generator);

            // Make sure compilation was successful.
            Assert.Empty(diagnostics);
            Assert.Equal(1, generatedSources.Length);
            Assert.Equal(21, generatedSources[0].SourceText.Lines.Count);
        }
        public async Task TestEmitter()
        {
            // The functionality of the resulting code is tested via LoggerMessageGeneratedCodeTests.cs
            string[] sources = Directory.GetFiles("TestClasses");
            foreach (var src in sources)
            {
                var testSourceCode = await File.ReadAllTextAsync(src).ConfigureAwait(false);

                var(d, r) = await RoslynTestUtils.RunGenerator(
                    new LoggerMessageGenerator(),
                    new[] { typeof(ILogger).Assembly, typeof(LoggerMessageAttribute).Assembly },
                    new[] { testSourceCode }).ConfigureAwait(false);

                Assert.Empty(d);
                Assert.Single(r);
            }
        }
Example #4
0
        private async Task VerifyAgainstBaselineUsingFile(string filename, string testSourceCode)
        {
            string baseline = await File.ReadAllTextAsync(Path.Combine("Baselines", filename)).ConfigureAwait(false);

            string[] expectedLines = baseline.Replace("%VERSION%", typeof(LoggerMessageGenerator).Assembly.GetName().Version?.ToString())
                                     .Split(Environment.NewLine);

            var(d, r) = await RoslynTestUtils.RunGenerator(
                new LoggerMessageGenerator(),
                new[] { typeof(ILogger).Assembly, typeof(LoggerMessageAttribute).Assembly },
                new[] { testSourceCode }).ConfigureAwait(false);

            Assert.Empty(d);
            Assert.Single(r);

            Assert.True(CompareLines(expectedLines, r[0].SourceText,
                                     out string errorMessage), errorMessage);
        }
        private static async Task <IReadOnlyList <Diagnostic> > RunGenerator(
            string code,
            bool wrap                           = true,
            bool inNamespace                    = true,
            bool includeBaseReferences          = true,
            bool includeLoggingReferences       = true,
            CancellationToken cancellationToken = default)
        {
            var text = code;

            if (wrap)
            {
                var nspaceStart = "namespace Test {";
                var nspaceEnd   = "}";
                if (!inNamespace)
                {
                    nspaceStart = "";
                    nspaceEnd   = "";
                }

                text = $@"
                    {nspaceStart}
                    using Microsoft.Extensions.Logging;
                    {code}
                    {nspaceEnd}
                ";
            }

            Assembly[]? refs = null;
            if (includeLoggingReferences)
            {
                refs = new[] { typeof(ILogger).Assembly, typeof(LoggerMessageAttribute).Assembly };
            }

            var(d, r) = await RoslynTestUtils.RunGenerator(
                new LoggerMessageGenerator(),
                refs,
                new[] { text },
                includeBaseReferences : includeBaseReferences,
                cancellationToken : cancellationToken).ConfigureAwait(false);

            return(d);
        }