From 2908f4a2492d2fb249347b22d398fde123ffc957 Mon Sep 17 00:00:00 2001 From: Cezary Piatek Date: Thu, 8 Nov 2018 20:40:43 +0100 Subject: [PATCH 1/9] #49 Implement Invocation scaffolding code fix --- ...InvocationScaffoldingTestCases.Designer.cs | 259 ++++++++++++++++++ .../InvocationScaffoldingTestCases.resx | 145 ++++++++++ .../InvocationScaffoldingTests.cs | 41 +++ ...ationScaffolding_With_RegularArguments.txt | 15 + ...caffolding_With_RegularArguments_FIXED.txt | 15 + ...ocationScaffolding_With_NamedArguments.txt | 15 + ...nScaffolding_With_NamedArguments_FIXED.txt | 15 + ...ationScaffolding_With_RegularArguments.txt | 18 ++ ...caffolding_With_RegularArguments_FIXED.txt | 18 ++ ...ocationScaffolding_With_NamedArguments.txt | 18 ++ ...nScaffolding_With_NamedArguments_FIXED.txt | 18 ++ .../MappingGenerator.Test.csproj | 9 + .../MappingGenerator.Vsix.csproj | 1 + .../InvocationScaffoldingCodeFixProvider.cs | 65 +++++ .../MappingGenerator/MappingGenerator.csproj | 19 -- ...ocalVariablesAsParameterCodeFixProvider.cs | 42 ++- 16 files changed, 680 insertions(+), 33 deletions(-) create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTestCases.Designer.cs create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTestCases.resx create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTests.cs create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments.txt create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments_FIXED.txt create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments.txt create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments_FIXED.txt create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments.txt create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments_FIXED.txt create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments.txt create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments_FIXED.txt create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator/InvocationScaffoldingCodeFixProvider.cs diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTestCases.Designer.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTestCases.Designer.cs new file mode 100644 index 0000000..9a1154d --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTestCases.Designer.cs @@ -0,0 +1,259 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace MappingGenerator.Test.InvocationScaffolding { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class InvocationScaffoldingTestCases { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal InvocationScaffoldingTestCases() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MappingGenerator.Test.InvocationScaffolding.InvocationScaffoldingTestCases", typeof(InvocationScaffoldingTestCases).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to namespace Scaffolding + ///{ + /// public static class SampleClass + /// { + /// public static void DoSth() + /// { + /// DoSthElse(); + /// } + /// + /// + /// public static void DoSthElse(string parameter1, int parameter2) + /// { + /// } + /// } + ///}. + /// + internal static string _001_MethodInvocationScaffolding_With_RegularArguments { + get { + return ResourceManager.GetString("_001_MethodInvocationScaffolding_With_RegularArguments", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to namespace Scaffolding + ///{ + /// public static class SampleClass + /// { + /// public static void DoSth() + /// { + /// DoSthElse("lorem ipsum", 32); + /// } + /// + /// + /// public static void DoSthElse(string parameter1, int parameter2) + /// { + /// } + /// } + ///}. + /// + internal static string _001_MethodInvocationScaffolding_With_RegularArguments_FIXED { + get { + return ResourceManager.GetString("_001_MethodInvocationScaffolding_With_RegularArguments_FIXED", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to namespace Scaffolding + ///{ + /// public static class SampleClass + /// { + /// public static void DoSth() + /// { + /// DoSthElse(); + /// } + /// + /// + /// public static void DoSthElse(string parameter1, int parameter2) + /// { + /// } + /// } + ///}. + /// + internal static string _002_MethodInvocationScaffolding_With_NamedArguments { + get { + return ResourceManager.GetString("_002_MethodInvocationScaffolding_With_NamedArguments", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to namespace Scaffolding + ///{ + /// public static class SampleClass + /// { + /// public static void DoSth() + /// { + /// DoSthElse("lorem ipsum", 32); + /// } + /// + /// + /// public static void DoSthElse(string parameter1, int parameter2) + /// { + /// } + /// } + ///}. + /// + internal static string _002_MethodInvocationScaffolding_With_NamedArguments_FIXED { + get { + return ResourceManager.GetString("_002_MethodInvocationScaffolding_With_NamedArguments_FIXED", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to namespace Scaffolding + ///{ + /// public static class SampleClass + /// { + /// public static AnotherClass DoSth() + /// { + /// return new AnotherClass(); + /// } + /// + /// + /// public class AnotherClass + /// { + /// public AnotherClass(string parameter1, int parameter2) + /// { + /// } + /// } + /// } + ///}. + /// + internal static string _003_ConstructorInvocationScaffolding_With_RegularArguments { + get { + return ResourceManager.GetString("_003_ConstructorInvocationScaffolding_With_RegularArguments", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to namespace Scaffolding + ///{ + /// public static class SampleClass + /// { + /// public static AnotherClass DoSth() + /// { + /// return new AnotherClass("lorem ipsum", 32); + /// } + /// + /// + /// public class AnotherClass + /// { + /// public AnotherClass(string parameter1, int parameter2) + /// { + /// } + /// } + /// } + ///}. + /// + internal static string _003_ConstructorInvocationScaffolding_With_RegularArguments_FIXED { + get { + return ResourceManager.GetString("_003_ConstructorInvocationScaffolding_With_RegularArguments_FIXED", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to namespace Scaffolding + ///{ + /// public static class SampleClass + /// { + /// public static AnotherClass DoSth() + /// { + /// return new AnotherClass(); + /// } + /// + /// + /// public class AnotherClass + /// { + /// public AnotherClass(string parameter1, int parameter2) + /// { + /// } + /// } + /// } + ///}. + /// + internal static string _004_ConstructorInvocationScaffolding_With_NamedArguments { + get { + return ResourceManager.GetString("_004_ConstructorInvocationScaffolding_With_NamedArguments", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to namespace Scaffolding + ///{ + /// public static class SampleClass + /// { + /// public static AnotherClass DoSth() + /// { + /// return new AnotherClass(parameter1: "lorem ipsum", parameter2: 32); + /// } + /// + /// + /// public class AnotherClass + /// { + /// public AnotherClass(string parameter1, int parameter2) + /// { + /// } + /// } + /// } + ///}. + /// + internal static string _004_ConstructorInvocationScaffolding_With_NamedArguments_FIXED { + get { + return ResourceManager.GetString("_004_ConstructorInvocationScaffolding_With_NamedArguments_FIXED", resourceCulture); + } + } + } +} diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTestCases.resx b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTestCases.resx new file mode 100644 index 0000000..c729633 --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTestCases.resx @@ -0,0 +1,145 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + TestData\001_MethodInvocationScaffolding_With_RegularArguments.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + + TestData\001_MethodInvocationScaffolding_With_RegularArguments_FIXED.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + + TestData\002_MethodInvocationScaffolding_With_NamedArguments.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + + TestData\002_MethodInvocationScaffolding_With_NamedArguments_FIXED.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + + TestData\003_ConstructorInvocationScaffolding_With_RegularArguments.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + + TestData\003_ConstructorInvocationScaffolding_With_RegularArguments_FIXED.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + + TestData\004_ConstructorInvocationScaffolding_With_NamedArguments.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + + TestData\004_ConstructorInvocationScaffolding_With_NamedArguments_FIXED.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTests.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTests.cs new file mode 100644 index 0000000..a8b46f2 --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTests.cs @@ -0,0 +1,41 @@ +using Microsoft.CodeAnalysis.CodeFixes; +using NUnit.Framework; +using TestHelper; +using static MappingGenerator.Test.InvocationScaffolding.InvocationScaffoldingTestCases; + +namespace MappingGenerator.Test.InvocationScaffolding +{ + public class InvocationScaffoldingTests: CodeFixVerifier + { + [Test] + public void should_be_able_to_scaffold_method_invocation_using_regular_arguments() + { + VerifyCSharpFix(_001_MethodInvocationScaffolding_With_RegularArguments, _001_MethodInvocationScaffolding_With_RegularArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036); + } + + [Test] + public void should_be_able_to_scaffold_method_invocation_using_named_arguments() + { + VerifyCSharpFix(_002_MethodInvocationScaffolding_With_NamedArguments, _002_MethodInvocationScaffolding_With_NamedArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036, 1); + } + + [Test] + public void should_be_able_to_scaffold_constructor_invocation_using_regular_arguments() + { + VerifyCSharpFix(_003_ConstructorInvocationScaffolding_With_RegularArguments, _003_ConstructorInvocationScaffolding_With_RegularArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036); + + } + + [Test] + public void should_be_able_to_scaffold_constructor_invocation_using_named_arguments() + { + VerifyCSharpFix(_004_ConstructorInvocationScaffolding_With_NamedArguments, _004_ConstructorInvocationScaffolding_With_NamedArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036, 1); + + } + + protected override CodeFixProvider GetCSharpCodeFixProvider() + { + return new InvocationScaffoldingCodeFixProvider(); + } + } +} diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments.txt new file mode 100644 index 0000000..52f0a01 --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments.txt @@ -0,0 +1,15 @@ +namespace Scaffolding +{ + public static class SampleClass + { + public static void DoSth() + { + DoSthElse(); + } + + + public static void DoSthElse(string parameter1, int parameter2) + { + } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments_FIXED.txt new file mode 100644 index 0000000..f13ca1f --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments_FIXED.txt @@ -0,0 +1,15 @@ +namespace Scaffolding +{ + public static class SampleClass + { + public static void DoSth() + { + DoSthElse("lorem ipsum", 32); + } + + + public static void DoSthElse(string parameter1, int parameter2) + { + } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments.txt new file mode 100644 index 0000000..52f0a01 --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments.txt @@ -0,0 +1,15 @@ +namespace Scaffolding +{ + public static class SampleClass + { + public static void DoSth() + { + DoSthElse(); + } + + + public static void DoSthElse(string parameter1, int parameter2) + { + } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments_FIXED.txt new file mode 100644 index 0000000..d16df9d --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments_FIXED.txt @@ -0,0 +1,15 @@ +namespace Scaffolding +{ + public static class SampleClass + { + public static void DoSth() + { + DoSthElse(parameter1: "lorem ipsum", parameter2: 32); + } + + + public static void DoSthElse(string parameter1, int parameter2) + { + } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments.txt new file mode 100644 index 0000000..01f1ee7 --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments.txt @@ -0,0 +1,18 @@ +namespace Scaffolding +{ + public static class SampleClass + { + public static AnotherClass DoSth() + { + return new AnotherClass(); + } + + + public class AnotherClass + { + public AnotherClass(string parameter1, int parameter2) + { + } + } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments_FIXED.txt new file mode 100644 index 0000000..06db93f --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments_FIXED.txt @@ -0,0 +1,18 @@ +namespace Scaffolding +{ + public static class SampleClass + { + public static AnotherClass DoSth() + { + return new AnotherClass("lorem ipsum", 32); + } + + + public class AnotherClass + { + public AnotherClass(string parameter1, int parameter2) + { + } + } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments.txt new file mode 100644 index 0000000..01f1ee7 --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments.txt @@ -0,0 +1,18 @@ +namespace Scaffolding +{ + public static class SampleClass + { + public static AnotherClass DoSth() + { + return new AnotherClass(); + } + + + public class AnotherClass + { + public AnotherClass(string parameter1, int parameter2) + { + } + } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments_FIXED.txt new file mode 100644 index 0000000..3b0357b --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments_FIXED.txt @@ -0,0 +1,18 @@ +namespace Scaffolding +{ + public static class SampleClass + { + public static AnotherClass DoSth() + { + return new AnotherClass(parameter1: "lorem ipsum", parameter2: 32); + } + + + public class AnotherClass + { + public AnotherClass(string parameter1, int parameter2) + { + } + } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator.Test.csproj b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator.Test.csproj index 1c3558f..71308d7 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator.Test.csproj +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator.Test.csproj @@ -71,6 +71,11 @@ True True + + True + True + InvocationScaffoldingTestCases.resx + True True @@ -101,6 +106,10 @@ ImplementCloneMethodTestCases.Designer.cs ResXFileCodeGenerator + + ResXFileCodeGenerator + InvocationScaffoldingTestCases.Designer.cs + ResXFileCodeGenerator MappingGeneratorTestCases.Designer.cs diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Vsix/MappingGenerator.Vsix.csproj b/MappingGenerator/MappingGenerator/MappingGenerator.Vsix/MappingGenerator.Vsix.csproj index 6b297c6..fe5baae 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Vsix/MappingGenerator.Vsix.csproj +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Vsix/MappingGenerator.Vsix.csproj @@ -56,6 +56,7 @@ DEBUG;TRACE prompt 4 + True pdbonly diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/InvocationScaffoldingCodeFixProvider.cs b/MappingGenerator/MappingGenerator/MappingGenerator/InvocationScaffoldingCodeFixProvider.cs new file mode 100644 index 0000000..7d296f9 --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator/InvocationScaffoldingCodeFixProvider.cs @@ -0,0 +1,65 @@ +using System.Composition; +using System.Collections.Immutable; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MappingGenerator.MethodHelpers; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Editing; + +namespace MappingGenerator +{ + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(InvocationScaffoldingCodeFixProvider)), Shared] + public class InvocationScaffoldingCodeFixProvider : CodeFixProvider + { + public const string CS7036 = nameof(CS7036); + + public sealed override ImmutableArray FixableDiagnosticIds => ImmutableArray.Create(CS7036); + + public sealed override FixAllProvider GetFixAllProvider() + { + return WellKnownFixAllProviders.BatchFixer; + } + + public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + var diagnostic = context.Diagnostics.First(); + var token = root.FindToken(diagnostic.Location.SourceSpan.Start); + var invocationExpression = token.Parent.FindNearestContainer(); + var invocation = GetInvocation(invocationExpression); + if (invocation is null) + { + return; + } + context.RegisterCodeFix(CodeAction.Create("Scaffold invocation (regular arguments)",c => ScaffoldInvocation(context.Document, invocation, namedArguments: false, cancellationToken: c), equivalenceKey: "Scaffold invocation (regular arguments)"), diagnostic); + context.RegisterCodeFix(CodeAction.Create("Scaffold invocation (named arguments)", c => ScaffoldInvocation(context.Document, invocation, namedArguments: true, cancellationToken: c), equivalenceKey: "Scaffold invocation (named arguments)"), diagnostic); + } + + private async Task ScaffoldInvocation(Document document, IInvocation invocation, bool namedArguments, + CancellationToken cancellationToken) + { + var syntaxGenerator = SyntaxGenerator.GetGenerator(document); + var semanticModel = await document.GetSemanticModelAsync(cancellationToken); + var contextAssembly = semanticModel.FindContextAssembly(invocation.SourceNode); + var mappingSourceFinder = new ScaffoldingSourceFinder(syntaxGenerator,document, contextAssembly); + return await CodeFixHelper.FixInvocationWithParameters(document, invocation, namedArguments, semanticModel, mappingSourceFinder, cancellationToken); + } + + private static IInvocation GetInvocation(SyntaxNode invocationExpression) + { + switch (invocationExpression) + { + case InvocationExpressionSyntax ie: + return new MethodInvocation(ie); + case ObjectCreationExpressionSyntax oce: + return new ConstructorInvocation(oce); + default: + return null; + } + } + } +} diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/MappingGenerator.csproj b/MappingGenerator/MappingGenerator/MappingGenerator/MappingGenerator.csproj index 54e1c89..35bd89a 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/MappingGenerator.csproj +++ b/MappingGenerator/MappingGenerator/MappingGenerator/MappingGenerator.csproj @@ -33,25 +33,6 @@ - - Code - - - Code - - - Code - - - Code - - - - Code - - - Code - diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/UseLocalVariablesAsParameterCodeFixProvider.cs b/MappingGenerator/MappingGenerator/MappingGenerator/UseLocalVariablesAsParameterCodeFixProvider.cs index 5ceca57..c94c8e1 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/UseLocalVariablesAsParameterCodeFixProvider.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/UseLocalVariablesAsParameterCodeFixProvider.cs @@ -15,6 +15,33 @@ namespace MappingGenerator { + public class CodeFixHelper + { + public static async Task FixInvocationWithParameters(Document document, + IInvocation invocation, + bool generateNamedParameters, + SemanticModel semanticModel, + IMappingSourceFinder mappingSourceFinder, + CancellationToken cancellationToken) + { + var syntaxGenerator = SyntaxGenerator.GetGenerator(document); + var overloadParameterSets = invocation.GetOverloadParameterSets(semanticModel); + if (overloadParameterSets != null) + { + var contextAssembly = semanticModel.FindContextAssembly(invocation.SourceNode); + var mappingEngine = new MappingEngine(semanticModel, syntaxGenerator, contextAssembly); + var parametersMatch = MethodHelper.FindBestParametersMatch(mappingSourceFinder, overloadParameterSets); + if (parametersMatch != null) + { + var argumentList = parametersMatch.ToArgumentListSyntax(mappingEngine, generateNamedParameters); + return await document.ReplaceNodes(invocation.SourceNode, invocation.WithArgumentList(argumentList), cancellationToken); + } + } + + return document; + } + } + [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(UseLocalVariablesAsParameterCodeFixProvider)), Shared] public class UseLocalVariablesAsParameterCodeFixProvider : CodeFixProvider { @@ -137,21 +164,8 @@ private static ITypeSymbol GetExpressionType(SemanticModel semanticModel, Syntax private async Task UseLocalVariablesAsParameters(Document document, IInvocation invocation, bool generateNamedParameters, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken); - var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var mappingSourceFinder = new LocalScopeMappingSourceFinder(semanticModel, invocation.SourceNode); - var overloadParameterSets = invocation.GetOverloadParameterSets(semanticModel); - if (overloadParameterSets != null) - { - var contextAssembly = semanticModel.FindContextAssembly(invocation.SourceNode); - var mappingEngine = new MappingEngine(semanticModel, syntaxGenerator, contextAssembly); - var parametersMatch = MethodHelper.FindBestParametersMatch(mappingSourceFinder, overloadParameterSets); - if (parametersMatch != null) - { - var argumentList = parametersMatch.ToArgumentListSyntax(mappingEngine, generateNamedParameters); - return await document.ReplaceNodes(invocation.SourceNode, invocation.WithArgumentList(argumentList), cancellationToken); - } - } - return document; + return await CodeFixHelper.FixInvocationWithParameters(document, invocation, generateNamedParameters, semanticModel, mappingSourceFinder, cancellationToken); } } } From 1711d2f5b5f6362173ebf1d9e9488fc9765589ae Mon Sep 17 00:00:00 2001 From: Cezary Piatek Date: Sat, 24 Nov 2018 21:28:51 +0100 Subject: [PATCH 2/9] Improve scaffolding for DateTime, Enum, Generics and abstract classes --- .../ScaffoldingSourceFinder.cs | 79 ++++++++++++++++--- 1 file changed, 67 insertions(+), 12 deletions(-) diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/ScaffoldingSourceFinder.cs b/MappingGenerator/MappingGenerator/MappingGenerator/ScaffoldingSourceFinder.cs index 6b46ba8..02e489a 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/ScaffoldingSourceFinder.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/ScaffoldingSourceFinder.cs @@ -44,10 +44,16 @@ internal SyntaxNode GetDefaultExpression(ITypeSymbol type, MappingPath mappingPa return syntaxGenerator.DefaultExpression(type) .WithTrailingTrivia(SyntaxFactory.Comment(" /* Stop recursive mapping */")); } - + + if (type.TypeKind == TypeKind.Struct && type.Name == "Nullable" && type is INamedTypeSymbol nullable) + { + type = nullable.TypeArguments.First(); + } + + if (type.TypeKind == TypeKind.Enum && type is INamedTypeSymbol namedTypeSymbol) { - var enumOptions = namedTypeSymbol.MemberNames.ToList(); + var enumOptions = namedTypeSymbol.MemberNames.Where(x=>x!="value__" && x!=".ctor").ToList(); if (enumOptions.Count > 0) { return syntaxGenerator.MemberAccessExpression(syntaxGenerator.IdentifierName(namedTypeSymbol.Name), syntaxGenerator.IdentifierName(enumOptions[0])); @@ -102,26 +108,56 @@ internal SyntaxNode GetDefaultExpression(ITypeSymbol type, MappingPath mappingPa { var nt = type as INamedTypeSymbol; + if (nt == null) + { + var genericTypeConstraints = type.UnwrapGeneric().ToList(); + if (genericTypeConstraints.Any() == false) + { + return GetDefaultForUnknown(type, SyntaxFactory.ParseTypeName("object")); + } + nt = genericTypeConstraints.FirstOrDefault(x=>x.TypeKind == TypeKind.Class) as INamedTypeSymbol ?? + genericTypeConstraints.FirstOrDefault(x => x.TypeKind == TypeKind.Interface) as INamedTypeSymbol; + } + + if (nt == null) + { + return GetDefaultForUnknownType(type); + } + if (nt.TypeKind == TypeKind.Interface) { - var implementations = SymbolFinder.FindImplementationsAsync(nt, this._document.Project.Solution).Result; + var implementations = SymbolFinder.FindImplementationsAsync(type, this._document.Project.Solution).Result; var firstImplementation = implementations.FirstOrDefault(); if (firstImplementation is INamedTypeSymbol == false) { - return syntaxGenerator.DefaultExpression(nt) - .WithTrailingTrivia(SyntaxFactory.Comment($" /* Cannot find any type implementing {nt.Name} */")); + return GetDefaultForUnknownType(type); } nt = firstImplementation as INamedTypeSymbol; - objectCreationExpression = - (ObjectCreationExpressionSyntax) syntaxGenerator.ObjectCreationExpression(nt); + objectCreationExpression = (ObjectCreationExpressionSyntax) syntaxGenerator.ObjectCreationExpression(nt); + }else if (nt.TypeKind == TypeKind.Class && nt.IsAbstract) + { + var randomDerived = SymbolFinder.FindDerivedClassesAsync(nt, this._document.Project.Solution).Result + .FirstOrDefault(x => x.IsAbstract == false); + + if (randomDerived != null) + { + nt = randomDerived; + objectCreationExpression = (ObjectCreationExpressionSyntax)syntaxGenerator.ObjectCreationExpression(nt); + } } - var hasDefaultConstructor = nt.Constructors.Any(x => x.Parameters.Length == 0); - if (hasDefaultConstructor == false && nt.Constructors.Length >0) + var publicConstructors = nt.Constructors.Where(x => + x.DeclaredAccessibility == Accessibility.Public || + (x.DeclaredAccessibility == Accessibility.Internal && + x.ContainingAssembly.IsSameAssemblyOrHasFriendAccessTo(_contextAssembly))).ToList(); + + + var hasDefaultConstructor = publicConstructors.Any(x => x.Parameters.Length == 0); + if (hasDefaultConstructor == false && publicConstructors.Count > 0) { - var randomConstructor = nt.Constructors.First(); + var randomConstructor = publicConstructors.First(); var constructorArguments = randomConstructor.Parameters.Select(p => GetDefaultExpression(p.Type, mappingPath.Clone())).ToList(); objectCreationExpression = (ObjectCreationExpressionSyntax)syntaxGenerator.ObjectCreationExpression(nt, constructorArguments); } @@ -145,6 +181,11 @@ internal SyntaxNode GetDefaultExpression(ITypeSymbol type, MappingPath mappingPa } + return GetDefaultForSpecialType(type); + } + + private SyntaxNode GetDefaultForSpecialType(ITypeSymbol type) + { switch (type.SpecialType) { case SpecialType.System_Boolean: @@ -175,13 +216,27 @@ internal SyntaxNode GetDefaultExpression(ITypeSymbol type, MappingPath mappingPa return syntaxGenerator.LiteralExpression("lorem ipsum"); case SpecialType.System_Decimal: return syntaxGenerator.LiteralExpression(2.0m); + case SpecialType.System_DateTime: + return syntaxGenerator.MemberAccessExpression(SyntaxFactory.IdentifierName("DateTime"), "Now"); case SpecialType.System_Object: - return SyntaxFactory.ObjectCreationExpression((TypeSyntax)syntaxGenerator.TypeExpression(type), SyntaxFactory.ArgumentList(),default(InitializerExpressionSyntax)); + return SyntaxFactory.ObjectCreationExpression((TypeSyntax) syntaxGenerator.TypeExpression(type), + SyntaxFactory.ArgumentList(), default(InitializerExpressionSyntax)); default: - return syntaxGenerator.LiteralExpression("ccc"); + return syntaxGenerator.LiteralExpression("/*TODO: provide value*/"); } } + private SyntaxNode GetDefaultForUnknownType(ITypeSymbol type) + { + return syntaxGenerator.DefaultExpression(type) + .WithTrailingTrivia(SyntaxFactory.Comment($" /* Cannot find any type implementing {type.Name} */")); + } + + private SyntaxNode GetDefaultForUnknown(ITypeSymbol type, TypeSyntax objectType) + { + return syntaxGenerator.DefaultExpression(objectType) + .WithTrailingTrivia(SyntaxFactory.Comment($" /* Cannot find any type implementing {type.Name} */")); + } } public static class TypeSyntaxFactory From 860207d5a02794fd634f9ce2189c92d4b45cb72a Mon Sep 17 00:00:00 2001 From: Cezary Piatek Date: Sat, 24 Nov 2018 21:47:37 +0100 Subject: [PATCH 3/9] Fix issue with variables named prefixed with @ --- .../MappingGenerator/MappingGenerator/NameHelper.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/NameHelper.cs b/MappingGenerator/MappingGenerator/MappingGenerator/NameHelper.cs index 8bcde10..811d8f3 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/NameHelper.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/NameHelper.cs @@ -24,11 +24,12 @@ public static string CreateLambdaParameterName(SyntaxNode sourceList) public static string ToLocalVariableName(string proposalLocalName) { - var withoutForbiddenSigns = string.Join("",proposalLocalName.Trim().Split(ForbiddenSigns).Where(x=> string.IsNullOrWhiteSpace(x) == false).Select(x=> + var nameParts = proposalLocalName.Replace("@","").Trim().Split(ForbiddenSigns).Where(x=> string.IsNullOrWhiteSpace(x) == false).Select(x=> { var cleanElement = x.Trim(); return $"{cleanElement.Substring(0, 1).ToUpper()}{cleanElement.Substring(1)}"; - })); + }); + var withoutForbiddenSigns = string.Join("",nameParts); return $"{withoutForbiddenSigns.Substring(0, 1).ToLower()}{withoutForbiddenSigns.Substring(1)}"; } From 4dc8b92b6fe91ea0bad5c9f761ef5be48b53ae4b Mon Sep 17 00:00:00 2001 From: Cezary Piatek Date: Mon, 26 Nov 2018 16:51:03 +0100 Subject: [PATCH 4/9] Handle mapping Nullable to T --- .../MappingGenerator/MappingEngine.cs | 9 +++++++++ .../MappingGenerator/ScaffoldingSourceFinder.cs | 4 ++-- .../MappingGenerator/SymbolHelper.cs | 17 +++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/MappingEngine.cs b/MappingGenerator/MappingGenerator/MappingGenerator/MappingEngine.cs index f56cbf9..05a3c90 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/MappingEngine.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/MappingEngine.cs @@ -68,6 +68,15 @@ public MappingElement MapExpression(MappingElement element, ITypeSymbol targetTy }; } + if (ObjectHelper.IsSimpleType(targetType) && SymbolHelper.IsNullable(sourceType, out var underlyingType) ) + { + element = new MappingElement() + { + Expression = (ExpressionSyntax)syntaxGenerator.MemberAccessExpression(element.Expression, "Value"), + ExpressionType = underlyingType + }; + } + if (IsUnwrappingNeeded(targetType, element)) { return TryToUnwrap(targetType, element); diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/ScaffoldingSourceFinder.cs b/MappingGenerator/MappingGenerator/MappingGenerator/ScaffoldingSourceFinder.cs index 02e489a..b768ed0 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/ScaffoldingSourceFinder.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/ScaffoldingSourceFinder.cs @@ -45,9 +45,9 @@ internal SyntaxNode GetDefaultExpression(ITypeSymbol type, MappingPath mappingPa .WithTrailingTrivia(SyntaxFactory.Comment(" /* Stop recursive mapping */")); } - if (type.TypeKind == TypeKind.Struct && type.Name == "Nullable" && type is INamedTypeSymbol nullable) + if (SymbolHelper.IsNullable(type, out var underlyingType)) { - type = nullable.TypeArguments.First(); + type = underlyingType; } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/SymbolHelper.cs b/MappingGenerator/MappingGenerator/MappingGenerator/SymbolHelper.cs index 5f24832..910302d 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/SymbolHelper.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/SymbolHelper.cs @@ -164,5 +164,22 @@ private static bool IsAutoGetter(AccessorDeclarationSyntax x) { return x.IsKind(SyntaxKind.GetAccessorDeclaration) && x.Body ==null && x.ExpressionBody == null; } + + public static bool IsNullable(ITypeSymbol type, out ITypeSymbol underlyingType) + { + if (type.TypeKind == TypeKind.Struct && type.Name == "Nullable") + { + underlyingType = GetUnderlyingNullableType(type); + return true; + } + + underlyingType = null; + return false; + } + + public static ITypeSymbol GetUnderlyingNullableType(ITypeSymbol type) + { + return ((INamedTypeSymbol) type).TypeArguments.First(); + } } } \ No newline at end of file From c27f0e12c8529418b936451348207967437c7714 Mon Sep 17 00:00:00 2001 From: Cezary Piatek Date: Mon, 26 Nov 2018 23:23:16 +0100 Subject: [PATCH 5/9] Handle multiparameter pure mapping function --- .../LocalScopeMappingSourceFinder.cs | 22 ++++++++++++++++++- .../MappingGeneratorRefactoring.cs | 13 ++++++++--- .../MappingGenerator/SymbolHelper.cs | 5 +++++ 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/LocalScopeMappingSourceFinder.cs b/MappingGenerator/MappingGenerator/MappingGenerator/LocalScopeMappingSourceFinder.cs index 8a6693a..cf7254c 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/LocalScopeMappingSourceFinder.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/LocalScopeMappingSourceFinder.cs @@ -18,6 +18,12 @@ public LocalScopeMappingSourceFinder(SemanticModel semanticModel, SyntaxNode nod this.localSymbols = semanticModel.LookupSymbols(nodeFromScope.GetLocation().SourceSpan.Start).Where(x=>x.Kind == SymbolKind.Local || x.Kind == SymbolKind.Parameter).ToList(); } + public LocalScopeMappingSourceFinder(SemanticModel semanticModel, IMethodSymbol methodSymbol) + { + this.semanticModel = semanticModel; + this.localSymbols = methodSymbol.Parameters; + } + public LocalScopeMappingSourceFinder(SemanticModel semanticModel, IReadOnlyList localSymbols) { this.semanticModel = semanticModel; @@ -35,13 +41,27 @@ public MappingElement FindMappingSource(string targetName, ITypeSymbol targetTyp return new MappingElement() { ExpressionType = type, - Expression = SyntaxFactory.IdentifierName(candidate.Name) + Expression = CreateIdentifierName(candidate) }; } } return null; } + private static IdentifierNameSyntax CreateIdentifierName(ISymbol candidate) + { + var identifier = candidate.Name; + bool isAnyKeyword = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None + || SyntaxFacts.GetContextualKeywordKind(identifier) != SyntaxKind.None; + + if (isAnyKeyword) + { + return SyntaxFactory.IdentifierName("@"+identifier); + } + + return SyntaxFactory.IdentifierName(identifier); + } + private ITypeSymbol GetType(ISymbol symbol) { var syntaxType = GetSyntaxType(symbol); diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/MappingGeneratorRefactoring.cs b/MappingGenerator/MappingGenerator/MappingGenerator/MappingGeneratorRefactoring.cs index 7634540..7db3672 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/MappingGeneratorRefactoring.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/MappingGeneratorRefactoring.cs @@ -42,9 +42,10 @@ private async Task TryToRegisterRefactoring(CodeRefactoringContext context, Synt } if (SymbolHelper.IsPureMappingFunction(methodSymbol) || + SymbolHelper.IsMultiParameterPureFunction(methodSymbol) || SymbolHelper.IsUpdateThisObjectFunction(methodSymbol) || SymbolHelper.IsUpdateParameterFunction(methodSymbol) || - SymbolHelper.IsMultiParameterUpdateThisObjectFunction(methodSymbol) + SymbolHelper.IsMultiParameterUpdateThisObjectFunction(methodSymbol) ) { context.RegisterRefactoring(CodeAction.Create(title: title, createChangedDocument: c => GenerateMappingMethodBody(context.Document, methodDeclaration, c), equivalenceKey: title)); @@ -96,8 +97,14 @@ private static IEnumerable GenerateMappingCode(IMethodSymbol methodS var newExpression = mappingEngine.MapExpression((ExpressionSyntax)generator.IdentifierName(source.Name), source.Type, targetType); return new[] { generator.ReturnStatement(newExpression).WithAdditionalAnnotations(Formatter.Annotation) }; } - - //TODO: Pure mapping with multiple parameters + + if (SymbolHelper.IsMultiParameterPureFunction(methodSymbol)) + { + var targetType = methodSymbol.ReturnType; + var sourceFinder = new LocalScopeMappingSourceFinder(semanticModel, methodSymbol); + var newExpression = mappingEngine.AddInitializerWithMapping((ObjectCreationExpressionSyntax)generator.ObjectCreationExpression(targetType), sourceFinder, targetType); + return new[] { generator.ReturnStatement(newExpression).WithAdditionalAnnotations(Formatter.Annotation) }; + } if (SymbolHelper.IsUpdateParameterFunction(methodSymbol)) { diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/SymbolHelper.cs b/MappingGenerator/MappingGenerator/MappingGenerator/SymbolHelper.cs index 910302d..a968601 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/SymbolHelper.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/SymbolHelper.cs @@ -181,5 +181,10 @@ public static ITypeSymbol GetUnderlyingNullableType(ITypeSymbol type) { return ((INamedTypeSymbol) type).TypeArguments.First(); } + + public static bool IsMultiParameterPureFunction(IMethodSymbol methodSymbol) + { + return methodSymbol.Parameters.Length > 1 && methodSymbol.ReturnsVoid == false; + } } } \ No newline at end of file From fadb397e12df005f196412117f5bb62010a841d2 Mon Sep 17 00:00:00 2001 From: Cezary Piatek Date: Wed, 28 Nov 2018 16:45:22 +0100 Subject: [PATCH 6/9] Stop reporting MappingGenerator refactoring on interfaces --- .../MappingGenerator/MappingGeneratorRefactoring.cs | 2 +- .../MappingGenerator/MappingGenerator/ObjectHelper.cs | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/MappingGeneratorRefactoring.cs b/MappingGenerator/MappingGenerator/MappingGenerator/MappingGeneratorRefactoring.cs index 7db3672..072f222 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/MappingGeneratorRefactoring.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/MappingGeneratorRefactoring.cs @@ -31,7 +31,7 @@ private async Task TryToRegisterRefactoring(CodeRefactoringContext context, Synt switch (node) { case MethodDeclarationSyntax methodDeclaration: - if (methodDeclaration.ParameterList.Parameters.Count > 0) + if (methodDeclaration.Parent.Kind() != SyntaxKind.InterfaceDeclaration && methodDeclaration.ParameterList.Parameters.Count > 0) { var semanticModel = await context.Document.GetSemanticModelAsync(); var methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration); diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/ObjectHelper.cs b/MappingGenerator/MappingGenerator/MappingGenerator/ObjectHelper.cs index eafb9c5..b638c4e 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/ObjectHelper.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/ObjectHelper.cs @@ -110,8 +110,14 @@ public static IEnumerable GetFieldsThaCanBeSetPublicly(ITypeSym public static bool IsSameAssemblyOrHasFriendAccessTo(this IAssemblySymbol assembly, IAssemblySymbol toAssembly) { + var areEquals = assembly.Equals(toAssembly); + if (areEquals == false && toAssembly == null) + { + return false; + } + return - Equals(assembly, toAssembly) || + areEquals || (assembly.IsInteractive && toAssembly.IsInteractive) || toAssembly.GivesAccessTo(assembly); } From 390e6c7bf0e86a09f62fbdc5340aaa2cf8eb9d85 Mon Sep 17 00:00:00 2001 From: Cezary Piatek Date: Wed, 5 Dec 2018 20:01:10 +0100 Subject: [PATCH 7/9] Replace standard test helpers with RoslynNunitLight references via git submodule --- .gitmodules | 4 + MappingGenerator/MappingGenerator.sln | 10 +- .../ExplicitConversionTests.cs | 21 +- ..._ExplicitConversionForInvalidAssigment.txt | 2 +- ...002_ExplicitConversionForInvalidReturn.txt | 2 +- .../003_ExplicitConversionForInvalidYield.txt | 2 +- ...nversionForInvalidAssigmentInInitBlock.txt | 2 +- .../InvocationScaffoldingTests.cs | 21 +- ...ationScaffolding_With_RegularArguments.txt | 2 +- ...ocationScaffolding_With_NamedArguments.txt | 2 +- ...ationScaffolding_With_RegularArguments.txt | 2 +- ...ocationScaffolding_With_NamedArguments.txt | 2 +- .../MappingGenerator.Test.csproj | 36 +-- .../Splatting/SplattingTestCases.Designer.cs | 9 +- .../Splatting/SplattingTestCases.resx | 16 +- .../Splatting/SplattingTests.cs | 18 +- ...cs => 001_SplattingInMethodInvocation.txt} | 2 +- ...odInvocationWithNamedParameters_FIXED.txt} | 0 ...001_SplattingInMethodInvocation_FIXED.txt} | 0 ... 002_SplattingInConstructorInvocation.txt} | 2 +- ...orInvocationWithNamedParameters_FIXED.txt} | 0 ...plattingInConstructorInvocation_FIXED.txt} | 0 ...=> 003_SplattingWithBestOverloadMatch.txt} | 2 +- ..._SplattingWithBestOverloadMatch_FIXED.txt} | 0 ...caVariablesToCompleteMethodInvocation.txt} | 2 +- ...odInvocationWithNamedParameters_Fixed.txt} | 0 ...ablesToCompleteMethodInvocation_Fixed.txt} | 0 ...iablesToCompleteConstructorInvocation.txt} | 2 +- ...rInvocationWithNamedParameters_Fixed .txt} | 0 ...ToCompleteConstructorInvocation_Fixed.txt} | 0 .../UseLocalVariablesTestCases.Designer.cs | 30 +- .../UseLocalVariablesTestCases.resx | 12 +- .../UserLocalVariablesAsParametersTests.cs | 16 +- .../Verifiers/CodeFixVerifier.cs | 207 ------------- .../Verifiers/DiagnosticVerifier.cs | 283 ------------------ .../MappingGenerator/RoslynNunitLight | 1 + 36 files changed, 103 insertions(+), 607 deletions(-) create mode 100644 .gitmodules rename MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/{001_SplattingInMethodInvocation.cs => 001_SplattingInMethodInvocation.txt} (93%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/{001_SplattingInMethodInvocationWithNamedParameters_FIXED.cs => 001_SplattingInMethodInvocationWithNamedParameters_FIXED.txt} (100%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/{001_SplattingInMethodInvocation_FIXED.cs => 001_SplattingInMethodInvocation_FIXED.txt} (100%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/{002_SplattingInConstructorInvocation.cs => 002_SplattingInConstructorInvocation.txt} (93%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/{002_SplattingInConstructorInvocationWithNamedParameters_FIXED.cs => 002_SplattingInConstructorInvocationWithNamedParameters_FIXED.txt} (100%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/{002_SplattingInConstructorInvocation_FIXED.cs => 002_SplattingInConstructorInvocation_FIXED.txt} (100%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/{003_SplattingWithBestOverloadMatch.cs => 003_SplattingWithBestOverloadMatch.txt} (93%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/{003_SplattingWithBestOverloadMatch_FIXED.cs => 003_SplattingWithBestOverloadMatch_FIXED.txt} (100%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/{001_UserLocaVariablesToCompleteMethodInvocation.cs => 001_UserLocaVariablesToCompleteMethodInvocation.txt} (92%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/{001_UserLocaVariablesToCompleteMethodInvocationWithNamedParameters_Fixed.cs => 001_UserLocaVariablesToCompleteMethodInvocationWithNamedParameters_Fixed.txt} (100%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/{001_UserLocaVariablesToCompleteMethodInvocation_Fixed.cs => 001_UserLocaVariablesToCompleteMethodInvocation_Fixed.txt} (100%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/{002_UserLocaVariablesToCompleteConstructorInvocation.cs => 002_UserLocaVariablesToCompleteConstructorInvocation.txt} (93%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/{002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed .cs => 002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed .txt} (100%) rename MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/{002_UserLocaVariablesToCompleteConstructorInvocation_Fixed.cs => 002_UserLocaVariablesToCompleteConstructorInvocation_Fixed.txt} (100%) delete mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/Verifiers/CodeFixVerifier.cs delete mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/Verifiers/DiagnosticVerifier.cs create mode 160000 MappingGenerator/MappingGenerator/RoslynNunitLight diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..8ca43ea --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "MappingGenerator/MappingGenerator/RoslynNunitLight"] + path = MappingGenerator/MappingGenerator/RoslynNunitLight + url = https://github.com/cezarypiatek/RoslynNUnitLight.NetStandard.git + branch = feature/add_diagnosticid_to_testcodefix diff --git a/MappingGenerator/MappingGenerator.sln b/MappingGenerator/MappingGenerator.sln index edcc840..abd7dcb 100644 --- a/MappingGenerator/MappingGenerator.sln +++ b/MappingGenerator/MappingGenerator.sln @@ -3,12 +3,14 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.27130.0 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MappingGenerator", "MappingGenerator\MappingGenerator\MappingGenerator.csproj", "{0C4641A8-C31D-4317-B099-ABD40115B5B2}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MappingGenerator", "MappingGenerator\MappingGenerator\MappingGenerator.csproj", "{0C4641A8-C31D-4317-B099-ABD40115B5B2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MappingGenerator.Test", "MappingGenerator\MappingGenerator.Test\MappingGenerator.Test.csproj", "{56A1DED8-DC1E-4B62-9D86-CE20EC30655C}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MappingGenerator.Test", "MappingGenerator\MappingGenerator.Test\MappingGenerator.Test.csproj", "{56A1DED8-DC1E-4B62-9D86-CE20EC30655C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MappingGenerator.Vsix", "MappingGenerator\MappingGenerator.Vsix\MappingGenerator.Vsix.csproj", "{D8BF5CFC-E3F0-4D2A-8131-508023BD0A30}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RoslynNUnitLight.NetStandard", "MappingGenerator\RoslynNunitLight\RoslynNUnitLight.NetStandard\RoslynNUnitLight.NetStandard.csproj", "{83A95CF7-A278-4D62-89F6-35736CE2BD4C}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -27,6 +29,10 @@ Global {D8BF5CFC-E3F0-4D2A-8131-508023BD0A30}.Debug|Any CPU.Build.0 = Debug|Any CPU {D8BF5CFC-E3F0-4D2A-8131-508023BD0A30}.Release|Any CPU.ActiveCfg = Release|Any CPU {D8BF5CFC-E3F0-4D2A-8131-508023BD0A30}.Release|Any CPU.Build.0 = Release|Any CPU + {83A95CF7-A278-4D62-89F6-35736CE2BD4C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {83A95CF7-A278-4D62-89F6-35736CE2BD4C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {83A95CF7-A278-4D62-89F6-35736CE2BD4C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {83A95CF7-A278-4D62-89F6-35736CE2BD4C}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/ExplicitConversionTests.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/ExplicitConversionTests.cs index 5c232f3..de860ce 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/ExplicitConversionTests.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/ExplicitConversionTests.cs @@ -1,42 +1,41 @@ -using System; -using System.Collections.Generic; -using System.Text; +using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using NUnit.Framework; -using TestHelper; +using RoslynNUnitLight; namespace MappingGenerator.Test.ExplicitConversions { - public class ExplicitConversionTests: CodeFixVerifier + public class ExplicitConversionTests: CodeFixTestFixture { [Test] - public void should_be_able_to_generate_conversion_for_invalid_assigment() + public void should_be_able_to_generate_conversion_for_invalid_assignment() { - VerifyCSharpFix(ExplicitConversionTestCases._001_ExplicitConversionForInvalidAssigment, ExplicitConversionTestCases._001_ExplicitConversionForInvalidAssigment_FIXED, ExplicitConversionCodeFixProvider.CS0029, 0); + TestCodeFix(ExplicitConversionTestCases._001_ExplicitConversionForInvalidAssigment, ExplicitConversionTestCases._001_ExplicitConversionForInvalidAssigment_FIXED, ExplicitConversionCodeFixProvider.CS0029, 0); } [Test] public void should_be_able_to_generate_conversion_for_invalid_return_statement() { - VerifyCSharpFix(ExplicitConversionTestCases._002_ExplicitConversionForInvalidReturn, ExplicitConversionTestCases._002_ExplicitConversionForInvalidReturn_FIXED, ExplicitConversionCodeFixProvider.CS0266, 0); + TestCodeFix(ExplicitConversionTestCases._002_ExplicitConversionForInvalidReturn, ExplicitConversionTestCases._002_ExplicitConversionForInvalidReturn_FIXED, ExplicitConversionCodeFixProvider.CS0266, 0); } [Test] public void should_be_able_to_generate_conversion_for_invalid_yield_statement() { - VerifyCSharpFix(ExplicitConversionTestCases._003_ExplicitConversionForInvalidYield, ExplicitConversionTestCases._003_ExplicitConversionForInvalidYield_FIXED, ExplicitConversionCodeFixProvider.CS0029, 0); + TestCodeFix(ExplicitConversionTestCases._003_ExplicitConversionForInvalidYield, ExplicitConversionTestCases._003_ExplicitConversionForInvalidYield_FIXED, ExplicitConversionCodeFixProvider.CS0029, 0); } [Test] public void should_be_able_to_generate_conversion_for_invalid_assignment_statement_in_init_block() { - VerifyCSharpFix(ExplicitConversionTestCases._004_ExplicitConversionForInvalidAssigmentInInitBlock, ExplicitConversionTestCases._004_ExplicitConversionForInvalidAssigmentInInitBlock_FIXED, ExplicitConversionCodeFixProvider.CS0029, 0); + TestCodeFix(ExplicitConversionTestCases._004_ExplicitConversionForInvalidAssigmentInInitBlock, ExplicitConversionTestCases._004_ExplicitConversionForInvalidAssigmentInInitBlock_FIXED, ExplicitConversionCodeFixProvider.CS0029, 0); } + protected override string LanguageName => LanguageNames.CSharp; - protected override CodeFixProvider GetCSharpCodeFixProvider() + protected override CodeFixProvider CreateProvider() { return new ExplicitConversionCodeFixProvider(); } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/001_ExplicitConversionForInvalidAssigment.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/001_ExplicitConversionForInvalidAssigment.txt index 0b16fa4..30f22e9 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/001_ExplicitConversionForInvalidAssigment.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/001_ExplicitConversionForInvalidAssigment.txt @@ -11,7 +11,7 @@ namespace MappingGenerator.Test.ExplicitConversions.TestCaseData public void DoSomething() { var addressEntity = new AddressEntity(); - this.Address = addressEntity; + this.Address = [|addressEntity|]; } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/002_ExplicitConversionForInvalidReturn.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/002_ExplicitConversionForInvalidReturn.txt index c3020ea..d408dfa 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/002_ExplicitConversionForInvalidReturn.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/002_ExplicitConversionForInvalidReturn.txt @@ -11,7 +11,7 @@ namespace MappingGenerator.Test.ExplicitConversions.TestCaseData public ReadOnlyCollection DoSomething(IList addresses) { - return addresses; + return [|addresses|]; } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/003_ExplicitConversionForInvalidYield.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/003_ExplicitConversionForInvalidYield.txt index 6858c64..9c264c4 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/003_ExplicitConversionForInvalidYield.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/003_ExplicitConversionForInvalidYield.txt @@ -8,7 +8,7 @@ namespace MappingGenerator.Test.ExplicitConversions.TestCaseData public IEnumerable DoSomething(AddressEntity address) { - yield return address; + yield return [|address|]; } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/004_ExplicitConversionForInvalidAssigmentInInitBlock.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/004_ExplicitConversionForInvalidAssigmentInInitBlock.txt index b3aa87b..f6e9220 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/004_ExplicitConversionForInvalidAssigmentInInitBlock.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ExplicitConversions/TestCaseData/004_ExplicitConversionForInvalidAssigmentInInitBlock.txt @@ -12,7 +12,7 @@ namespace MappingGenerator.Test.ExplicitConversions.TestCaseData { var addressEntity = new AddressEntity(); return new UserDTO{ - Address = addressEntity + Address = [|addressEntity|] } } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTests.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTests.cs index a8b46f2..c56d275 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTests.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/InvocationScaffoldingTests.cs @@ -1,41 +1,44 @@ -using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeFixes; using NUnit.Framework; +using RoslynNUnitLight; using TestHelper; using static MappingGenerator.Test.InvocationScaffolding.InvocationScaffoldingTestCases; namespace MappingGenerator.Test.InvocationScaffolding { - public class InvocationScaffoldingTests: CodeFixVerifier + public class InvocationScaffoldingTests: CodeFixTestFixture { [Test] public void should_be_able_to_scaffold_method_invocation_using_regular_arguments() { - VerifyCSharpFix(_001_MethodInvocationScaffolding_With_RegularArguments, _001_MethodInvocationScaffolding_With_RegularArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036); + TestCodeFix(_001_MethodInvocationScaffolding_With_RegularArguments, _001_MethodInvocationScaffolding_With_RegularArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036); } [Test] public void should_be_able_to_scaffold_method_invocation_using_named_arguments() { - VerifyCSharpFix(_002_MethodInvocationScaffolding_With_NamedArguments, _002_MethodInvocationScaffolding_With_NamedArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036, 1); + TestCodeFix(_002_MethodInvocationScaffolding_With_NamedArguments, _002_MethodInvocationScaffolding_With_NamedArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036, 1); } [Test] public void should_be_able_to_scaffold_constructor_invocation_using_regular_arguments() { - VerifyCSharpFix(_003_ConstructorInvocationScaffolding_With_RegularArguments, _003_ConstructorInvocationScaffolding_With_RegularArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036); + TestCodeFix(_003_ConstructorInvocationScaffolding_With_RegularArguments, _003_ConstructorInvocationScaffolding_With_RegularArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036); } [Test] public void should_be_able_to_scaffold_constructor_invocation_using_named_arguments() { - VerifyCSharpFix(_004_ConstructorInvocationScaffolding_With_NamedArguments, _004_ConstructorInvocationScaffolding_With_NamedArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036, 1); - + TestCodeFix(_004_ConstructorInvocationScaffolding_With_NamedArguments, _004_ConstructorInvocationScaffolding_With_NamedArguments_FIXED, InvocationScaffoldingCodeFixProvider.CS7036, 1); } - protected override CodeFixProvider GetCSharpCodeFixProvider() + protected override string LanguageName => LanguageNames.CSharp; + + protected override CodeFixProvider CreateProvider() { - return new InvocationScaffoldingCodeFixProvider(); + return new InvocationScaffoldingCodeFixProvider(); } } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments.txt index 52f0a01..348d6e2 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/001_MethodInvocationScaffolding_With_RegularArguments.txt @@ -4,7 +4,7 @@ { public static void DoSth() { - DoSthElse(); + [|DoSthElse()|]; } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments.txt index 52f0a01..348d6e2 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/002_MethodInvocationScaffolding_With_NamedArguments.txt @@ -4,7 +4,7 @@ { public static void DoSth() { - DoSthElse(); + [|DoSthElse()|]; } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments.txt index 01f1ee7..26e5fd3 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/003_ConstructorInvocationScaffolding_With_RegularArguments.txt @@ -4,7 +4,7 @@ { public static AnotherClass DoSth() { - return new AnotherClass(); + return new [|AnotherClass()|]; } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments.txt index 01f1ee7..26e5fd3 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/InvocationScaffolding/TestData/004_ConstructorInvocationScaffolding_With_NamedArguments.txt @@ -4,7 +4,7 @@ { public static AnotherClass DoSth() { - return new AnotherClass(); + return new [|AnotherClass()|]; } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator.Test.csproj b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator.Test.csproj index 71308d7..40fcf05 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator.Test.csproj +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator.Test.csproj @@ -6,40 +6,6 @@ true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -48,11 +14,11 @@ - + diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTestCases.Designer.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTestCases.Designer.cs index 37b8c1d..a697a93 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTestCases.Designer.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTestCases.Designer.cs @@ -72,7 +72,7 @@ internal SplattingTestCases() { /// public void DoSomething() /// { /// var user = new UserDTO(); - /// ProceessUser(user); + /// ProceessUser([|user|]); /// } /// /// public void ProceessUser(string firstName, string lastName, int age) @@ -85,7 +85,7 @@ internal SplattingTestCases() { /// public class UserDTO /// { /// public string FirstName { get; set; } - /// public string LastNa [rest of string was truncated]";. + /// public string La [rest of string was truncated]";. /// internal static string _001_SplattingInMethodInvocation { get { @@ -302,7 +302,7 @@ internal static string _003_SplattingWithBestOverloadMatch { /// public void DoSomething() /// { /// var user = new UserDTO(); - /// UserProcessor.ProceessUser(user); + /// UserProcessor.ProceessUser(firstName: user.FirstName, lastName: user.LastName, age: user.Age); /// } /// /// public void ProceessUser(string firstName, string lastName, int age) @@ -312,8 +312,7 @@ internal static string _003_SplattingWithBestOverloadMatch { /// } /// /// public class UserProcessor - /// { - /// public void ProceessUser(string firstName, string [rest of string was truncated]";. + /// [rest of string was truncated]";. /// internal static string _003_SplattingWithBestOverloadMatch_FIXED { get { diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTestCases.resx b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTestCases.resx index d2aed37..01f77a9 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTestCases.resx +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTestCases.resx @@ -119,27 +119,27 @@ - TestCaseData\001_SplattingInMethodInvocation.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\001_SplattingInMethodInvocation.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\001_SplattingInMethodInvocationWithNamedParameters_FIXED.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\001_SplattingInMethodInvocationWithNamedParameters_FIXED.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\001_SplattingInMethodInvocation_FIXED.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\001_SplattingInMethodInvocation_FIXED.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\002_SplattingInConstructorInvocation.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\002_SplattingInConstructorInvocation.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\002_SplattingInConstructorInvocationWithNamedParameters_FIXED.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\002_SplattingInConstructorInvocationWithNamedParameters_FIXED.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\002_SplattingInConstructorInvocation_FIXED.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\002_SplattingInConstructorInvocation_FIXED.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\003_SplattingWithBestOverloadMatch.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\003_SplattingWithBestOverloadMatch.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\003_SplattingWithBestOverloadMatch_FIXED.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\003_SplattingWithBestOverloadMatch_FIXED.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTests.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTests.cs index 4a37c7f..bb90ed8 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTests.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/SplattingTests.cs @@ -1,43 +1,45 @@ using Microsoft.CodeAnalysis.CodeFixes; -using TestHelper; using MappingGenerator.Test.Splatting; +using Microsoft.CodeAnalysis; using NUnit.Framework; +using RoslynNUnitLight; namespace MappingGenerator.Test { - public class SplattingTests : CodeFixVerifier + public class SplattingTests : CodeFixTestFixture { [Test] public void should_be_able_to_generate_splatting_for_method_invocation_with_regular_parameters() { - VerifyCSharpFix(SplattingTestCases._001_SplattingInMethodInvocation, SplattingTestCases._001_SplattingInMethodInvocation_FIXED, SplattingCodeFixProvider.CS7036, 0); + TestCodeFix(SplattingTestCases._001_SplattingInMethodInvocation, SplattingTestCases._001_SplattingInMethodInvocation_FIXED, SplattingCodeFixProvider.CS7036, 0); } [Test] public void should_be_able_to_generate_splatting_for_method_invocation_with_named_parameters() { - VerifyCSharpFix(SplattingTestCases._001_SplattingInMethodInvocation, SplattingTestCases._001_SplattingInMethodInvocationWithNamedParameters_FIXED, SplattingCodeFixProvider.CS7036, 1); + TestCodeFix(SplattingTestCases._001_SplattingInMethodInvocation, SplattingTestCases._001_SplattingInMethodInvocationWithNamedParameters_FIXED, SplattingCodeFixProvider.CS7036, 1); } [Test] public void should_be_able_to_generate_splatting_for_constructor_invocation_with_regular_parameters() { - VerifyCSharpFix(SplattingTestCases._002_SplattingInConstructorInvocation, SplattingTestCases._002_SplattingInConstructorInvocation_FIXED, SplattingCodeFixProvider.CS7036, 0); + TestCodeFix(SplattingTestCases._002_SplattingInConstructorInvocation, SplattingTestCases._002_SplattingInConstructorInvocation_FIXED, SplattingCodeFixProvider.CS7036, 0); } [Test] public void should_be_able_to_generate_splatting_for_constructor_invocation_with_named_parameters() { - VerifyCSharpFix(SplattingTestCases._002_SplattingInConstructorInvocation, SplattingTestCases._002_SplattingInConstructorInvocationWithNamedParameters_FIXED, SplattingCodeFixProvider.CS7036, 1); + TestCodeFix(SplattingTestCases._002_SplattingInConstructorInvocation, SplattingTestCases._002_SplattingInConstructorInvocationWithNamedParameters_FIXED, SplattingCodeFixProvider.CS7036, 1); } [Test] public void should_be_able_to_generate_splatting_for_best_method_overload() { - VerifyCSharpFix(SplattingTestCases._003_SplattingWithBestOverloadMatch, SplattingTestCases._003_SplattingWithBestOverloadMatch_FIXED, SplattingCodeFixProvider.CS1501, 1); + TestCodeFix(SplattingTestCases._003_SplattingWithBestOverloadMatch, SplattingTestCases._003_SplattingWithBestOverloadMatch_FIXED, SplattingCodeFixProvider.CS1501, 1); } - protected override CodeFixProvider GetCSharpCodeFixProvider() + protected override string LanguageName => LanguageNames.CSharp; + protected override CodeFixProvider CreateProvider() { return new SplattingCodeFixProvider(); } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocation.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocation.txt similarity index 93% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocation.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocation.txt index cd218f1..0332c35 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocation.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocation.txt @@ -9,7 +9,7 @@ class TestMapper public void DoSomething() { var user = new UserDTO(); - ProceessUser(user); + ProceessUser([|user|]); } public void ProceessUser(string firstName, string lastName, int age) diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocationWithNamedParameters_FIXED.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocationWithNamedParameters_FIXED.txt similarity index 100% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocationWithNamedParameters_FIXED.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocationWithNamedParameters_FIXED.txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocation_FIXED.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocation_FIXED.txt similarity index 100% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocation_FIXED.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/001_SplattingInMethodInvocation_FIXED.txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocation.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocation.txt similarity index 93% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocation.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocation.txt index aaccd30..b7f9e3e 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocation.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocation.txt @@ -9,7 +9,7 @@ class TestMapper public void DoSomething() { var user = new UserDTO(); - new SampleClass(user); + new SampleClass([|user|]); } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocationWithNamedParameters_FIXED.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocationWithNamedParameters_FIXED.txt similarity index 100% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocationWithNamedParameters_FIXED.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocationWithNamedParameters_FIXED.txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocation_FIXED.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocation_FIXED.txt similarity index 100% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocation_FIXED.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/002_SplattingInConstructorInvocation_FIXED.txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/003_SplattingWithBestOverloadMatch.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/003_SplattingWithBestOverloadMatch.txt similarity index 93% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/003_SplattingWithBestOverloadMatch.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/003_SplattingWithBestOverloadMatch.txt index 245dc25..8baa9b7 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/003_SplattingWithBestOverloadMatch.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/003_SplattingWithBestOverloadMatch.txt @@ -9,7 +9,7 @@ class TestMapper public void DoSomething() { var user = new UserDTO(); - UserProcessor.ProceessUser(user); + UserProcessor.ProceessUser([|user|]); } public void ProceessUser(string firstName, string lastName, int age) diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/003_SplattingWithBestOverloadMatch_FIXED.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/003_SplattingWithBestOverloadMatch_FIXED.txt similarity index 100% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/003_SplattingWithBestOverloadMatch_FIXED.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/Splatting/TestCaseData/003_SplattingWithBestOverloadMatch_FIXED.txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocation.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocation.txt similarity index 92% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocation.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocation.txt index c0899c2..a98a2fd 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocation.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocation.txt @@ -10,7 +10,7 @@ public void DoSomething(string firstName, string lastName) { var age = 33; var weight = 80m; - DoSomethingElse(); + [|DoSomethingElse()|]; } public void DoSomethingElse(string firstName, string lastName, int age, decimal weight) diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocationWithNamedParameters_Fixed.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocationWithNamedParameters_Fixed.txt similarity index 100% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocationWithNamedParameters_Fixed.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocationWithNamedParameters_Fixed.txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocation_Fixed.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocation_Fixed.txt similarity index 100% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocation_Fixed.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/001_UserLocaVariablesToCompleteMethodInvocation_Fixed.txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocation.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocation.txt similarity index 93% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocation.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocation.txt index 0324597..cf410c0 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocation.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocation.txt @@ -10,7 +10,7 @@ public void DoSomething(string firstName, string lastName) { var age = 33; var weight = 80m; - new SampleClass(); + new [|SampleClass()|]; } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed .cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed .txt similarity index 100% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed .cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed .txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocation_Fixed.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocation_Fixed.txt similarity index 100% rename from MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocation_Fixed.cs rename to MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/TestCaseData/002_UserLocaVariablesToCompleteConstructorInvocation_Fixed.txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UseLocalVariablesTestCases.Designer.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UseLocalVariablesTestCases.Designer.cs index 24033bb..eb1349b 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UseLocalVariablesTestCases.Designer.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UseLocalVariablesTestCases.Designer.cs @@ -153,15 +153,14 @@ internal static string _001_UserLocaVariablesToCompleteMethodInvocationWithNamed /// { /// var age = 33; /// var weight = 80m; - /// DoSomethingElse(); - /// } - /// - /// public void DoSomethingElse(string firstName, string lastName, int age, decimal weight) - /// { - /// + /// new SampleClass(); /// } /// } - ///}. + /// + /// public class SampleClass + /// { + /// public SampleClass(string firstName, string lastName, int age, decimal weight) + /// { /// [rest of string was truncated]";. /// internal static string _002_UserLocaVariablesToCompleteConstructorInvocation { get { @@ -182,13 +181,13 @@ internal static string _002_UserLocaVariablesToCompleteConstructorInvocation { /// { /// var age = 33; /// var weight = 80m; - /// DoSomethingElse(firstName, lastName, age, weight); + /// new SampleClass(firstName, lastName, age, weight); /// } + /// } /// - /// public void DoSomethingElse(string firstName, string lastName, int age, decimal weight) - /// { - /// - /// [rest of string was truncated]";. + /// public class SampleClass + /// { + /// public SampleClass(string firstName, string lastName, int [rest of string was truncated]";. /// internal static string _002_UserLocaVariablesToCompleteConstructorInvocation_Fixed { get { @@ -209,10 +208,13 @@ internal static string _002_UserLocaVariablesToCompleteConstructorInvocation_Fix /// { /// var age = 33; /// var weight = 80m; - /// DoSomethingElse(firstName: firstName, lastName: lastName, age: age, weight: weight); + /// new SampleClass(firstName: firstName, lastName: lastName, age: age, weight: weight); /// } + /// } /// - /// public void DoSomethingElse(string firstName, string lastName, int a [rest of string was truncated]";. + /// public class SampleClass + /// { + /// public SampleClass(strin [rest of string was truncated]";. /// internal static string _002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed { get { diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UseLocalVariablesTestCases.resx b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UseLocalVariablesTestCases.resx index 4b1a000..7a14270 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UseLocalVariablesTestCases.resx +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UseLocalVariablesTestCases.resx @@ -119,21 +119,21 @@ - TestCaseData\001_UserLocaVariablesToCompleteMethodInvocation.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\001_UserLocaVariablesToCompleteMethodInvocation.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\001_UserLocaVariablesToCompleteMethodInvocationWithNamedParameters_Fixed.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\001_UserLocaVariablesToCompleteMethodInvocationWithNamedParameters_Fixed.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\001_UserLocaVariablesToCompleteMethodInvocation_Fixed.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\001_UserLocaVariablesToCompleteMethodInvocation_Fixed.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\002_UserLocaVariablesToCompleteConstructorInvocation.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\002_UserLocaVariablesToCompleteConstructorInvocation.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed .cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed .txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 - TestCaseData\002_UserLocaVariablesToCompleteConstructorInvocation_Fixed.cs;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + TestCaseData\002_UserLocaVariablesToCompleteConstructorInvocation_Fixed.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UserLocalVariablesAsParametersTests.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UserLocalVariablesAsParametersTests.cs index 057c856..5d84ca5 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UserLocalVariablesAsParametersTests.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/UseLocalVariablesAsParameters/UserLocalVariablesAsParametersTests.cs @@ -1,38 +1,42 @@ using Microsoft.CodeAnalysis.CodeFixes; using TestHelper; using MappingGenerator.Test.UseLocalVariablesAsParameters; +using Microsoft.CodeAnalysis; using NUnit.Framework; +using RoslynNUnitLight; namespace MappingGenerator.Test { - public class UseLocalVariablesAsParameter : CodeFixVerifier + public class UseLocalVariablesAsParameter : CodeFixTestFixture { [Test] public void should_be_able_to_complete_method_invocation_with_local_variables_as_regular_parameters() { - VerifyCSharpFix(UseLocalVariablesTestCases._001_UserLocaVariablesToCompleteMethodInvocation, UseLocalVariablesTestCases._001_UserLocaVariablesToCompleteMethodInvocation_Fixed, UseLocalVariablesAsParameterCodeFixProvider.CS7036, 0); + TestCodeFix(UseLocalVariablesTestCases._001_UserLocaVariablesToCompleteMethodInvocation, UseLocalVariablesTestCases._001_UserLocaVariablesToCompleteMethodInvocation_Fixed, UseLocalVariablesAsParameterCodeFixProvider.CS7036, 0); } [Test] public void should_be_able_to_complete_method_invocation_with_local_variables_as_named_parameters() { - VerifyCSharpFix(UseLocalVariablesTestCases._001_UserLocaVariablesToCompleteMethodInvocation, UseLocalVariablesTestCases._001_UserLocaVariablesToCompleteMethodInvocationWithNamedParameters_Fixed, UseLocalVariablesAsParameterCodeFixProvider.CS7036, 1); + TestCodeFix(UseLocalVariablesTestCases._001_UserLocaVariablesToCompleteMethodInvocation, UseLocalVariablesTestCases._001_UserLocaVariablesToCompleteMethodInvocationWithNamedParameters_Fixed, UseLocalVariablesAsParameterCodeFixProvider.CS7036, 1); } [Test] public void should_be_able_to_complete_constructor_invocation_with_local_variables_as_regular_parameters() { - VerifyCSharpFix(UseLocalVariablesTestCases._002_UserLocaVariablesToCompleteConstructorInvocation, UseLocalVariablesTestCases._002_UserLocaVariablesToCompleteConstructorInvocation_Fixed, SplattingCodeFixProvider.CS7036, 0); + TestCodeFix(UseLocalVariablesTestCases._002_UserLocaVariablesToCompleteConstructorInvocation, UseLocalVariablesTestCases._002_UserLocaVariablesToCompleteConstructorInvocation_Fixed, SplattingCodeFixProvider.CS7036, 0); } [Test] public void should_be_able_to_complete_constructor_invocation_with_local_variables_as_named_parameters() { - VerifyCSharpFix(UseLocalVariablesTestCases._002_UserLocaVariablesToCompleteConstructorInvocation, UseLocalVariablesTestCases._002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed, SplattingCodeFixProvider.CS7036, 1); + TestCodeFix(UseLocalVariablesTestCases._002_UserLocaVariablesToCompleteConstructorInvocation, UseLocalVariablesTestCases._002_UserLocaVariablesToCompleteConstructorInvocationWithNamedParameters_Fixed, SplattingCodeFixProvider.CS7036, 1); } + + protected override string LanguageName => LanguageNames.CSharp; - protected override CodeFixProvider GetCSharpCodeFixProvider() + protected override CodeFixProvider CreateProvider() { return new UseLocalVariablesAsParameterCodeFixProvider(); } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Verifiers/CodeFixVerifier.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Verifiers/CodeFixVerifier.cs deleted file mode 100644 index 00abfd4..0000000 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Verifiers/CodeFixVerifier.cs +++ /dev/null @@ -1,207 +0,0 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CodeActions; -using Microsoft.CodeAnalysis.CodeFixes; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Formatting; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using NUnit.Framework; - -namespace TestHelper -{ - /// - /// Superclass of all Unit tests made for diagnostics with codefixes. - /// Contains methods used to verify correctness of codefixes - /// - public abstract partial class CodeFixVerifier : DiagnosticVerifier - { - /// - /// Returns the codefix being tested (C#) - to be implemented in non-abstract class - /// - /// The CodeFixProvider to be used for CSharp code - protected virtual CodeFixProvider GetCSharpCodeFixProvider() - { - return null; - } - - /// - /// Returns the codefix being tested (VB) - to be implemented in non-abstract class - /// - /// The CodeFixProvider to be used for VisualBasic code - protected virtual CodeFixProvider GetBasicCodeFixProvider() - { - return null; - } - - /// - /// Called to test a C# codefix when applied on the inputted string as a source - /// - /// A class in the form of a string before the CodeFix was applied to it - /// A class in the form of a string after the CodeFix was applied to it - /// Index determining which codefix to apply if there are multiple - /// A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied - protected void VerifyCSharpFix(string oldSource, string newSource, int? codeFixIndex = null, bool allowNewCompilerDiagnostics = false) - { - VerifyFix(LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), GetCSharpCodeFixProvider(), oldSource, newSource, codeFixIndex, allowNewCompilerDiagnostics); - } - - /// - /// Called to test a C# codefix when applied on the inputted string as a source - /// - /// A class in the form of a string before the CodeFix was applied to it - /// A class in the form of a string after the CodeFix was applied to it - /// Diagnostic id to fix - /// Index determining which codefix to apply if there are multiple - /// A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied - protected void VerifyCSharpFix(string oldSource, string newSource, string diagnosticId, int? codeFixIndex = null, bool allowNewCompilerDiagnostics = false) - { - VerifyFix(LanguageNames.CSharp, diagnosticId, GetCSharpCodeFixProvider(), oldSource, newSource, codeFixIndex, allowNewCompilerDiagnostics); - } - - /// - /// Called to test a VB codefix when applied on the inputted string as a source - /// - /// A class in the form of a string before the CodeFix was applied to it - /// A class in the form of a string after the CodeFix was applied to it - /// Index determining which codefix to apply if there are multiple - /// A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied - protected void VerifyBasicFix(string oldSource, string newSource, int? codeFixIndex = null, bool allowNewCompilerDiagnostics = false) - { - VerifyFix(LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), GetBasicCodeFixProvider(), oldSource, newSource, codeFixIndex, allowNewCompilerDiagnostics); - } - - /// - /// General verifier for codefixes. - /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes. - /// Then gets the string after the codefix is applied and compares it with the expected result. - /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true. - /// - /// The language the source code is in - /// The analyzer to be applied to the source code - /// The codefix to be applied to the code wherever the relevant Diagnostic is found - /// A class in the form of a string before the CodeFix was applied to it - /// A class in the form of a string after the CodeFix was applied to it - /// Index determining which codefix to apply if there are multiple - /// A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied - private void VerifyFix(string language, DiagnosticAnalyzer analyzer, CodeFixProvider codeFixProvider, string oldSource, string newSource, int? codeFixIndex, bool allowNewCompilerDiagnostics) - { - var document = CreateDocument(oldSource, language); - var analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, new[] { document }); - var compilerDiagnostics = GetCompilerDiagnostics(document); - var attempts = analyzerDiagnostics.Length; - - for (int i = 0; i < attempts; ++i) - { - var actions = new List(); - var context = new CodeFixContext(document, analyzerDiagnostics[0], (a, d) => actions.Add(a), CancellationToken.None); - codeFixProvider.RegisterCodeFixesAsync(context).Wait(); - - if (!actions.Any()) - { - break; - } - - if (codeFixIndex != null) - { - document = ApplyFix(document, actions.ElementAt((int)codeFixIndex)); - break; - } - - document = ApplyFix(document, actions.ElementAt(0)); - analyzerDiagnostics = GetSortedDiagnosticsFromDocuments(analyzer, new[] { document }); - - var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document)); - - //check if applying the code fix introduced any new compiler diagnostics - if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) - { - // Format and get the compiler diagnostics again so that the locations make sense in the output - document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace)); - newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document)); - - Assert.IsTrue(false, - string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n", - string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())), - document.GetSyntaxRootAsync().Result.ToFullString())); - } - - //check if there are analyzer diagnostics left after the code fix - if (!analyzerDiagnostics.Any()) - { - break; - } - } - - //after applying all of the code fixes, compare the resulting string to the inputted one - var actual = GetStringFromDocument(document); - Assert.AreEqual(newSource, actual); - } - - - /// - /// General verifier for codefixes. - /// Creates a Document from the source string, then gets diagnostics on it and applies the relevant codefixes. - /// Then gets the string after the codefix is applied and compares it with the expected result. - /// Note: If any codefix causes new diagnostics to show up, the test fails unless allowNewCompilerDiagnostics is set to true. - /// - /// The language the source code is in - /// /// Diagnostic id to fix - /// The codefix to be applied to the code wherever the relevant Diagnostic is found - /// A class in the form of a string before the CodeFix was applied to it - /// A class in the form of a string after the CodeFix was applied to it - /// Index determining which codefix to apply if there are multiple - /// A bool controlling whether or not the test will fail if the CodeFix introduces other warnings after being applied - private void VerifyFix(string language, string diagnosticId, CodeFixProvider codeFixProvider, string oldSource, string newSource, int? codeFixIndex, bool allowNewCompilerDiagnostics) - { - var document = CreateDocument(oldSource, language); - var compilerDiagnostics = GetCompilerDiagnostics(document); - - if (compilerDiagnostics.Any(x => x.Id == diagnosticId) == false) - { - var reportedIssues = compilerDiagnostics.Select(x => x.Id).ToList(); - Assert.Fail($"There is no issue reported for {diagnosticId}. Reported issues: {string.Join(',', reportedIssues)}"); - } - - - foreach (var diagnosticToFix in compilerDiagnostics.Where(x => x.Id == diagnosticId)) - { - var actions = new List(); - var context = new CodeFixContext(document, diagnosticToFix, (a, d) => actions.Add(a), CancellationToken.None); - codeFixProvider.RegisterCodeFixesAsync(context).Wait(); - - if (!actions.Any()) - { - break; - } - - if (codeFixIndex != null) - { - document = ApplyFix(document, actions.ElementAt((int)codeFixIndex)); - break; - } - - document = ApplyFix(document, actions.ElementAt(0)); - - var newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document)); - - //check if applying the code fix introduced any new compiler diagnostics - if (!allowNewCompilerDiagnostics && newCompilerDiagnostics.Any()) - { - // Format and get the compiler diagnostics again so that the locations make sense in the output - document = document.WithSyntaxRoot(Formatter.Format(document.GetSyntaxRootAsync().Result, Formatter.Annotation, document.Project.Solution.Workspace)); - newCompilerDiagnostics = GetNewDiagnostics(compilerDiagnostics, GetCompilerDiagnostics(document)); - - Assert.IsTrue(false, - string.Format("Fix introduced new compiler diagnostics:\r\n{0}\r\n\r\nNew document:\r\n{1}\r\n", - string.Join("\r\n", newCompilerDiagnostics.Select(d => d.ToString())), - document.GetSyntaxRootAsync().Result.ToFullString())); - } - } - - //after applying all of the code fixes, compare the resulting string to the inputted one - var actual = GetStringFromDocument(document); - Assert.AreEqual(newSource, actual); - } - } -} diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Verifiers/DiagnosticVerifier.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/Verifiers/DiagnosticVerifier.cs deleted file mode 100644 index 722a754..0000000 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/Verifiers/DiagnosticVerifier.cs +++ /dev/null @@ -1,283 +0,0 @@ -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using NUnit.Framework; - -namespace TestHelper -{ - /// - /// Superclass of all Unit Tests for DiagnosticAnalyzers - /// - public abstract partial class DiagnosticVerifier - { - #region To be implemented by Test classes - /// - /// Get the CSharp analyzer being tested - to be implemented in non-abstract class - /// - protected virtual DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() - { - return null; - } - - /// - /// Get the Visual Basic analyzer being tested (C#) - to be implemented in non-abstract class - /// - protected virtual DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() - { - return null; - } - #endregion - - #region Verifier wrappers - - /// - /// Called to test a C# DiagnosticAnalyzer when applied on the single inputted string as a source - /// Note: input a DiagnosticResult for each Diagnostic expected - /// - /// A class in the form of a string to run the analyzer on - /// DiagnosticResults that should appear after the analyzer is run on the source - protected void VerifyCSharpDiagnostic(string source, params DiagnosticResult[] expected) - { - VerifyDiagnostics(new[] { source }, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected); - } - - /// - /// Called to test a VB DiagnosticAnalyzer when applied on the single inputted string as a source - /// Note: input a DiagnosticResult for each Diagnostic expected - /// - /// A class in the form of a string to run the analyzer on - /// DiagnosticResults that should appear after the analyzer is run on the source - protected void VerifyBasicDiagnostic(string source, params DiagnosticResult[] expected) - { - VerifyDiagnostics(new[] { source }, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected); - } - - /// - /// Called to test a C# DiagnosticAnalyzer when applied on the inputted strings as a source - /// Note: input a DiagnosticResult for each Diagnostic expected - /// - /// An array of strings to create source documents from to run the analyzers on - /// DiagnosticResults that should appear after the analyzer is run on the sources - protected void VerifyCSharpDiagnostic(string[] sources, params DiagnosticResult[] expected) - { - VerifyDiagnostics(sources, LanguageNames.CSharp, GetCSharpDiagnosticAnalyzer(), expected); - } - - /// - /// Called to test a VB DiagnosticAnalyzer when applied on the inputted strings as a source - /// Note: input a DiagnosticResult for each Diagnostic expected - /// - /// An array of strings to create source documents from to run the analyzers on - /// DiagnosticResults that should appear after the analyzer is run on the sources - protected void VerifyBasicDiagnostic(string[] sources, params DiagnosticResult[] expected) - { - VerifyDiagnostics(sources, LanguageNames.VisualBasic, GetBasicDiagnosticAnalyzer(), expected); - } - - /// - /// General method that gets a collection of actual diagnostics found in the source after the analyzer is run, - /// then verifies each of them. - /// - /// An array of strings to create source documents from to run the analyzers on - /// The language of the classes represented by the source strings - /// The analyzer to be run on the source code - /// DiagnosticResults that should appear after the analyzer is run on the sources - private void VerifyDiagnostics(string[] sources, string language, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expected) - { - var diagnostics = GetSortedDiagnostics(sources, language, analyzer); - VerifyDiagnosticResults(diagnostics, analyzer, expected); - } - - #endregion - - #region Actual comparisons and verifications - /// - /// Checks each of the actual Diagnostics found and compares them with the corresponding DiagnosticResult in the array of expected results. - /// Diagnostics are considered equal only if the DiagnosticResultLocation, Id, Severity, and Message of the DiagnosticResult match the actual diagnostic. - /// - /// The Diagnostics found by the compiler after running the analyzer on the source code - /// The analyzer that was being run on the sources - /// Diagnostic Results that should have appeared in the code - private static void VerifyDiagnosticResults(IEnumerable actualResults, DiagnosticAnalyzer analyzer, params DiagnosticResult[] expectedResults) - { - int expectedCount = expectedResults.Count(); - int actualCount = actualResults.Count(); - - if (expectedCount > actualCount) - { - string diagnosticsOutput = actualResults.Any() ? FormatDiagnostics(analyzer, actualResults.ToArray()) : " NONE."; - Assert.Fail("Mismatch between number of diagnostics returned, expected \"{0}\" actual \"{1}\"\r\n\r\nDiagnostics:\r\n{2}\r\n", expectedCount, actualCount, diagnosticsOutput); - } - - var actualResultsList = actualResults.ToList(); - foreach (var expected in expectedResults) - { - foreach (var expectedLocation in expected.Locations) - { - var actual = actualResultsList.FirstOrDefault(x => - { - if (x.Id != expected.Id) - { - return false; - } - - var actualSpan = x.Location.GetLineSpan(); - - if (expectedLocation.Path != actualSpan.Path) - { - return false; - } - - var actualLinePosition = actualSpan.StartLinePosition; - if (actualLinePosition.Line > 0) - { - if (actualLinePosition.Line + 1 != expectedLocation.Line) - { - return false; - } - } - - - // Only check column position if there is an actual column position in the real diagnostic - if (actualLinePosition.Character > 0) - { - if (actualLinePosition.Character + 1 != expectedLocation.Column) - { - return false; - } - } - - return true; - }); - - - if (actual == null) - { - Assert.Fail("No diagnostic at expected locations {0},{1}", expectedLocation.Line, expectedLocation.Column); - } - - - if (expected.Line == -1 && expected.Column == -1) - { - if (actual.Location != Location.None) - { - Assert.Fail("Expected:\nA project diagnostic with No location\nActual:\n{0}", FormatDiagnostics(analyzer, actual)); - } - } - - - - if (actual.Severity != expected.Severity) - { - Assert.Fail("Expected diagnostic severity to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Severity, actual.Severity, FormatDiagnostics(analyzer, actual)); - } - - if (actual.GetMessage() != expected.Message) - { - Assert.Fail("Expected diagnostic message to be \"{0}\" was \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", expected.Message, actual.GetMessage(), FormatDiagnostics(analyzer, actual)); - } - } - } - } - - /// - /// Helper method to VerifyDiagnosticResult that checks the location of a diagnostic and compares it with the location in the expected DiagnosticResult. - /// - /// The analyzer that was being run on the sources - /// The diagnostic that was found in the code - /// The Location of the Diagnostic found in the code - /// The DiagnosticResultLocation that should have been found - private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticResultLocation expected) - { - var actualSpan = actual.GetLineSpan(); - - Assert.IsTrue(actualSpan.Path == expected.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test.")), - string.Format("Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", - expected.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic))); - - var actualLinePosition = actualSpan.StartLinePosition; - - // Only check line position if there is an actual line in the real diagnostic - if (actualLinePosition.Line > 0) - { - if (actualLinePosition.Line + 1 != expected.Line) - { - Assert.IsTrue(false, - string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", - expected.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic))); - } - } - - // Only check column position if there is an actual column position in the real diagnostic - if (actualLinePosition.Character > 0) - { - if (actualLinePosition.Character + 1 != expected.Column) - { - Assert.IsTrue(false, - string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n {2}\r\n", - expected.Column, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic))); - } - } - } - #endregion - - #region Formatting Diagnostics - /// - /// Helper method to format a Diagnostic into an easily readable string - /// - /// The analyzer that this verifier tests - /// The Diagnostics to be formatted - /// The Diagnostics formatted as a string - private static string FormatDiagnostics(DiagnosticAnalyzer analyzer, params Diagnostic[] diagnostics) - { - var builder = new StringBuilder(); - for (int i = 0; i < diagnostics.Length; ++i) - { - builder.AppendLine("// " + diagnostics[i].ToString()); - - var analyzerType = analyzer.GetType(); - var rules = analyzer.SupportedDiagnostics; - - foreach (var rule in rules) - { - if (rule != null && rule.Id == diagnostics[i].Id) - { - var location = diagnostics[i].Location; - if (location == Location.None) - { - builder.AppendFormat("GetGlobalResult({0}.{1})", analyzerType.Name, rule.Id); - } - else - { - Assert.IsTrue(location.IsInSource, - $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n"); - - string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt"; - var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition; - - builder.AppendFormat("{0}({1}, {2}, {3}.{4})", - resultMethodName, - linePosition.Line + 1, - linePosition.Character + 1, - analyzerType.Name, - rule.Id); - } - - if (i != diagnostics.Length - 1) - { - builder.Append(','); - } - - builder.AppendLine(); - break; - } - } - } - return builder.ToString(); - } - #endregion - } -} diff --git a/MappingGenerator/MappingGenerator/RoslynNunitLight b/MappingGenerator/MappingGenerator/RoslynNunitLight new file mode 160000 index 0000000..735e1ef --- /dev/null +++ b/MappingGenerator/MappingGenerator/RoslynNunitLight @@ -0,0 +1 @@ +Subproject commit 735e1efe5957d5e9d1b3b1b383b8b2b1f13f6af3 From 6a8dc71af8cf13c6e0e03987c5fa5032559072df Mon Sep 17 00:00:00 2001 From: Cezary Piatek Date: Wed, 5 Dec 2018 21:14:04 +0100 Subject: [PATCH 8/9] Add test cases for: - multiparameter pure mapping method - Nullable to T - DateTime scaffolding --- ...alizationBlockWithSampleDatComplexType.txt | 4 +- ...ionBlockWithSampleDatComplexType_FIXED.txt | 7 +- .../MappingGeneratorTestCases.Designer.cs | 58 +++++++++ .../MappingGeneratorTestCases.resx | 6 + .../MappingGenerator/MappingGeneratorTests.cs | 6 + .../TestCaseData/001_PureMappingMethod.txt | 3 + .../001_PureMappingMethod_FIXED.txt | 6 +- .../021_MultiParameterPureMappingMethod.txt | 113 +++++++++++++++++ ..._MultiParameterPureMappingMethod_FIxed.txt | 117 ++++++++++++++++++ 9 files changed, 316 insertions(+), 4 deletions(-) create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/021_MultiParameterPureMappingMethod.txt create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/021_MultiParameterPureMappingMethod_FIxed.txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/EmptyInitializationBlock/TestCasesData/005_CompleteInitializationBlockWithSampleDatComplexType.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/EmptyInitializationBlock/TestCasesData/005_CompleteInitializationBlockWithSampleDatComplexType.txt index ad23037..23d313e 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/EmptyInitializationBlock/TestCasesData/005_CompleteInitializationBlockWithSampleDatComplexType.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/EmptyInitializationBlock/TestCasesData/005_CompleteInitializationBlockWithSampleDatComplexType.txt @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Collections; using System.Collections.ObjectModel; +using System; namespace TestAutoMapper { @@ -31,7 +32,8 @@ namespace TestAutoMapper public ReadOnlyCollection InnersReadonly { get; set; } public IList NonGenericInners { get; set; } - + + public DateTime OccuredOn { get; set; } } class InnerDefaultObject diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/EmptyInitializationBlock/TestCasesData/005_CompleteInitializationBlockWithSampleDatComplexType_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/EmptyInitializationBlock/TestCasesData/005_CompleteInitializationBlockWithSampleDatComplexType_FIXED.txt index e34a7c4..fafee96 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/EmptyInitializationBlock/TestCasesData/005_CompleteInitializationBlockWithSampleDatComplexType_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/EmptyInitializationBlock/TestCasesData/005_CompleteInitializationBlockWithSampleDatComplexType_FIXED.txt @@ -1,6 +1,7 @@ using System.Collections.Generic; using System.Collections; using System.Collections.ObjectModel; +using System; namespace TestAutoMapper { @@ -31,7 +32,8 @@ namespace TestAutoMapper public ReadOnlyCollection InnersReadonly { get; set; } public IList NonGenericInners { get; set; } - + + public DateTime OccuredOn { get; set; } } class InnerDefaultObject @@ -158,7 +160,8 @@ namespace TestAutoMapper NonGenericInners = new ArrayList() { new object() - } + }, + OccuredOn = DateTime.Now }; } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.Designer.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.Designer.cs index 1532a6b..b152c33 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.Designer.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.Designer.cs @@ -1165,5 +1165,63 @@ internal static string _020_MappingPropertiesInConstructorInheritedFromLibraryCl return ResourceManager.GetString("_020_MappingPropertiesInConstructorInheritedFromLibraryClass_FIXED", resourceCulture); } } + + /// + /// Looks up a localized string similar to using System; + ///using System.Collections.Generic; + ///using System.Text; + ///using System.Collections.ObjectModel; + /// + ///namespace MappingGenerator.Test.MappingGenerator.TestCaseData + ///{ + /// public class TestMapper + /// { + /// public static UserDTO Map(string firstName, string lastName) + /// { + /// return new UserDTO + /// { + /// FirstName = firstName, + /// LastName = lastName + /// }; + /// } + /// } + /// + /// public class UserDTO + /// { + /// public string First [rest of string was truncated]";. + /// + internal static string _021_MultiParameterPureMappingMethod { + get { + return ResourceManager.GetString("_021_MultiParameterPureMappingMethod", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to using System; + ///using System.Collections.Generic; + ///using System.Text; + ///using System.Collections.ObjectModel; + /// + ///namespace MappingGenerator.Test.MappingGenerator.TestCaseData + ///{ + /// public class TestMapper + /// { + /// public static UserDTO [|Map|](string firstName, string lastName) + /// { + /// throw new NotImplementedException(); + /// } + /// } + /// + /// public class UserDTO + /// { + /// public string FirstName { get; } + /// public string LastName { get; private set; } + /// public [rest of string was truncated]";. + /// + internal static string _021_MultiParameterPureMappingMethod_FIxed { + get { + return ResourceManager.GetString("_021_MultiParameterPureMappingMethod_FIxed", resourceCulture); + } + } } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.resx b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.resx index 738d242..89fe786 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.resx +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.resx @@ -238,4 +238,10 @@ TestCaseData\020_MappingPropertiesInConstructorInheritedFromLibraryClass_FIXED.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + TestCaseData\021_MultiParameterPureMappingMethod.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + + TestCaseData\021_MultiParameterPureMappingMethod_FIxed.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTests.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTests.cs index a09ac8f..74d284a 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTests.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTests.cs @@ -134,6 +134,12 @@ public void should_be_able_to_map_properties_inside_constructor_inherited_from_c TestCodeRefactoring(_020_MappingPropertiesInConstructorInheritedFromLibraryClass, _020_MappingPropertiesInConstructorInheritedFromLibraryClass_FIXED); } + [Test] + public void should_be_able_to_implement_multi_parameter_pure_method() + { + TestCodeRefactoring(_021_MultiParameterPureMappingMethod, _021_MultiParameterPureMappingMethod_FIxed); + } + protected override string LanguageName => LanguageNames.CSharp; protected override CodeRefactoringProvider CreateProvider() diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod.txt index 093cc87..5ae7939 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod.txt @@ -29,6 +29,7 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData public AddressDTO MainAddress { get; set; } public ReadOnlyCollection Addresses { get; set; } public int UnitId { get; set; } + public decimal ExtraSavings { get; set; } } public class UserSourceDTO @@ -82,6 +83,8 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData { throw new NotImplementedException(); } + + public decimal? ExtraSavings { get; set; } } public class AddressEntity diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod_FIXED.txt index 8391ae7..b284e9d 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod_FIXED.txt @@ -37,7 +37,8 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData FlatNo = entityAddress.FlatNo, BuildingNo = entityAddress.BuildingNo }).ToList().AsReadOnly(), - UnitId = entity.Unit.Id + UnitId = entity.Unit.Id, + ExtraSavings = entity.ExtraSavings.Value }; } } @@ -58,6 +59,7 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData public AddressDTO MainAddress { get; set; } public ReadOnlyCollection Addresses { get; set; } public int UnitId { get; set; } + public decimal ExtraSavings { get; set; } } public class UserSourceDTO @@ -111,6 +113,8 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData { throw new NotImplementedException(); } + + public decimal? ExtraSavings { get; set; } } public class AddressEntity diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/021_MultiParameterPureMappingMethod.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/021_MultiParameterPureMappingMethod.txt new file mode 100644 index 0000000..1dd574d --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/021_MultiParameterPureMappingMethod.txt @@ -0,0 +1,113 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections.ObjectModel; + +namespace MappingGenerator.Test.MappingGenerator.TestCaseData +{ + public class TestMapper + { + public static UserDTO [|Map|](string firstName, string lastName) + { + throw new NotImplementedException(); + } + } + + public class UserDTO + { + public string FirstName { get; set;} + public string LastName { get; set; } + public int Age { get; set; } + public int Cash { get;} + public AccountDTO Account { get; private set; } + public List Debs { get; set; } + public UserSourceDTO Source { get; set; } + public string Login { get; set; } + public byte[] ImageData { get; set; } + public List LuckyNumbers { get; set; } + public int Total { get; set; } + public AddressDTO MainAddress { get; set; } + public ReadOnlyCollection Addresses { get; set; } + public int UnitId { get; set; } + } + + public class UserSourceDTO + { + public string ProviderName { get; set; } + public string ProviderAddress { get; set; } + + public UserSourceDTO(string providerName, string providerAddress) + { + ProviderName = providerName; + ProviderAddress = providerAddress; + } + } + + public class AccountDTO + { + public string BankName { get; set; } + public string Number { get; set; } + } + + public class AddressDTO + { + public string City { get; set; } + public string ZipCode { get; set; } + public string Street { get; set; } + public string FlatNo { get; set; } + public string BuildingNo { get; set; } + } + + //---- Entities + + public class UserEntity + { + public string FirstName { get; set; } + public string LastName { get; set; } + public int Age { get; set; } + public AccountEntity Account { get; set; } + public List Debs { get; set; } + public UserSourceEntity Source { get; set; } + public string Name { get; } + public CustomerKind Kind { get; set; } + public double Cash { get; } + public byte[] ImageData { get; set; } + public List LuckyNumbers { get; set; } + public AddressEntity MainAddress { get; set; } + public string AddressCity { get; set; } + public List Addresses { get; set; } + public UnitEntity Unit { get; set; } + + public int GetTotal() + { + throw new NotImplementedException(); + } + } + + public class AddressEntity + { + public string City { get; set; } + public string ZipCode { get; set; } + public string Street { get; set; } + public string FlatNo { get; set; } + public string BuildingNo { get; set; } + } + + public class UnitEntity + { + public int Id { get; set; } + public string Name { get; set; } + } + + public class UserSourceEntity + { + public string ProviderName { get; set; } + public string ProviderAddress { get; set; } + } + + public class AccountEntity + { + public string BankName { get; set; } + public string Number { get; set; } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/021_MultiParameterPureMappingMethod_FIxed.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/021_MultiParameterPureMappingMethod_FIxed.txt new file mode 100644 index 0000000..671619a --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/021_MultiParameterPureMappingMethod_FIxed.txt @@ -0,0 +1,117 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Collections.ObjectModel; + +namespace MappingGenerator.Test.MappingGenerator.TestCaseData +{ + public class TestMapper + { + public static UserDTO Map(string firstName, string lastName) + { + return new UserDTO() + { + FirstName = firstName, + LastName = lastName + }; + } + } + + public class UserDTO + { + public string FirstName { get; set;} + public string LastName { get; set; } + public int Age { get; set; } + public int Cash { get;} + public AccountDTO Account { get; private set; } + public List Debs { get; set; } + public UserSourceDTO Source { get; set; } + public string Login { get; set; } + public byte[] ImageData { get; set; } + public List LuckyNumbers { get; set; } + public int Total { get; set; } + public AddressDTO MainAddress { get; set; } + public ReadOnlyCollection Addresses { get; set; } + public int UnitId { get; set; } + } + + public class UserSourceDTO + { + public string ProviderName { get; set; } + public string ProviderAddress { get; set; } + + public UserSourceDTO(string providerName, string providerAddress) + { + ProviderName = providerName; + ProviderAddress = providerAddress; + } + } + + public class AccountDTO + { + public string BankName { get; set; } + public string Number { get; set; } + } + + public class AddressDTO + { + public string City { get; set; } + public string ZipCode { get; set; } + public string Street { get; set; } + public string FlatNo { get; set; } + public string BuildingNo { get; set; } + } + + //---- Entities + + public class UserEntity + { + public string FirstName { get; set; } + public string LastName { get; set; } + public int Age { get; set; } + public AccountEntity Account { get; set; } + public List Debs { get; set; } + public UserSourceEntity Source { get; set; } + public string Name { get; } + public CustomerKind Kind { get; set; } + public double Cash { get; } + public byte[] ImageData { get; set; } + public List LuckyNumbers { get; set; } + public AddressEntity MainAddress { get; set; } + public string AddressCity { get; set; } + public List Addresses { get; set; } + public UnitEntity Unit { get; set; } + + public int GetTotal() + { + throw new NotImplementedException(); + } + } + + public class AddressEntity + { + public string City { get; set; } + public string ZipCode { get; set; } + public string Street { get; set; } + public string FlatNo { get; set; } + public string BuildingNo { get; set; } + } + + public class UnitEntity + { + public int Id { get; set; } + public string Name { get; set; } + } + + public class UserSourceEntity + { + public string ProviderName { get; set; } + public string ProviderAddress { get; set; } + } + + public class AccountEntity + { + public string BankName { get; set; } + public string Number { get; set; } + } +} \ No newline at end of file From a49a36148126c1cb56865b4028c3e0bad43cc2c5 Mon Sep 17 00:00:00 2001 From: Cezary Piatek Date: Wed, 5 Dec 2018 22:39:49 +0100 Subject: [PATCH 9/9] Use ConvertAll for collection mapping if possible --- .../TestCaseData/001_DeepClone_FIXED.txt | 4 +- .../MappingGeneratorTestCases.Designer.cs | 129 +++++++++++++----- .../MappingGeneratorTestCases.resx | 6 + .../MappingGenerator/MappingGeneratorTests.cs | 6 + .../001_PureMappingMethod_FIXED.txt | 8 +- .../002_PureMappingMethodWithGenerics.txt | 2 +- ...02_PureMappingMethodWithGenerics_FIXED.txt | 6 +- ...MappingFromOneToAnotherParameter_FIXED.txt | 8 +- ...04_UpdateThisObjectWithSingleParameter.txt | 2 +- ...ateThisObjectWithSingleParameter_FIXED.txt | 6 +- ...6_ConstructorWithSingleParameter_FIXED.txt | 8 +- .../008_StopRecursingMapping_Fixed.txt | 4 +- .../009_IdentityFunctionMapping_FIXED.txt | 2 +- ...tityFunctionMappingForCollection_FIXED.txt | 6 +- ...gWithSingularLambdaParameterName_FIXED.txt | 4 +- ...WithPrefixedLambdaParameterName_FIXED..txt | 4 +- ...CollectionMappingWithGenericName_FIXED.txt | 4 +- ...ionMappingWithPostfixGenericName_FIXED.txt | 4 +- ...gularSingularLambdaParameterName_FIXED.txt | 4 +- ...lCaseSingularLambdaParameterName_FIXED.txt | 4 +- ...WithPostfixGenericNameInSingular_FIXED.txt | 4 +- .../022_CollectionMappingIListToList.txt | 26 ++++ ...022_CollectionMappingIListToList_Fixed.txt | 30 ++++ .../MappingGenerator/MappingEngine.cs | 10 +- README.md | 2 +- 25 files changed, 215 insertions(+), 78 deletions(-) create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/022_CollectionMappingIListToList.txt create mode 100644 MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/022_CollectionMappingIListToList_Fixed.txt diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ImplementCloneMethod/TestCaseData/001_DeepClone_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ImplementCloneMethod/TestCaseData/001_DeepClone_FIXED.txt index 55db9a3..f639a42 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/ImplementCloneMethod/TestCaseData/001_DeepClone_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/ImplementCloneMethod/TestCaseData/001_DeepClone_FIXED.txt @@ -32,11 +32,11 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData return new UserDTO() { Age = Age, - Debs = Debs.Select(thisDeb => new AccountDTO() + Debs = Debs.ConvertAll(thisDeb => new AccountDTO() { BankName = thisDeb.BankName, Number = thisDeb.Number - }).ToList(), + }), Source = new UserSourceDTO(providerName: Source.ProviderName, providerAddress: Source.ProviderAddress), Login = Login, ImageData = ImageData.ToArray(), diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.Designer.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.Designer.cs index b152c33..e4bf0a8 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.Designer.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.Designer.cs @@ -103,10 +103,10 @@ internal static string _001_PureMappingMethod { /// return new UserDTO() /// { /// Age = entity.Age, - /// Debs = entity.Debs.Select(entityDeb => new AccountDTO() + /// Debs = entity.Debs.ConvertAll(entityDeb => new AccountDTO() /// { /// BankName = entityDeb.BankName, - /// [rest of string was truncated]";. + /// [rest of string was truncated]";. /// internal static string _001_PureMappingMethod_FIXED { get { @@ -156,8 +156,8 @@ internal static string _002_PureMappingMethodWithGenerics { /// return new TDto() /// { /// Age = entity.Age, - /// Debs = entity.Debs.Select(entityDeb => new AccountDTO() - /// { /// [rest of string was truncated]";. + /// Debs = entity.Debs.ConvertAll(entityDeb => new AccountDTO() + /// [rest of string was truncated]";. /// internal static string _002_PureMappingMethodWithGenerics_FIXED { get { @@ -206,12 +206,12 @@ internal static string _003_MappingFromOneToAnotherParameter { /// public static void Map(UserEntity src, UserDTO dst) /// { /// dst.Age = src.Age; - /// dst.Debs = src.Debs.Select(srcDeb => new AccountDTO() + /// dst.Debs = src.Debs.ConvertAll(srcDeb => new AccountDTO() /// { /// BankName = srcDeb.BankName, /// Number = srcDeb.Number - /// }).ToList(); - /// [rest of string was truncated]";. + /// }); + /// [rest of string was truncated]";. /// internal static string _003_MappingFromOneToAnotherParameter_FIXED { get { @@ -439,10 +439,9 @@ internal static string _008_StopRecursingMapping { /// return new Model1Vm() /// { /// Id = src.Id, - /// Model2s = src.Model2s.Select(srcModel2 => new Model2Vm() + /// Model2s = src.Model2s.ConvertAll(srcModel2 => new Model2Vm() /// { - /// Id = srcModel2.Id, - /// [rest of string was truncated]";. + /// Id = srcModel2.Id, /// [rest of string was truncated]";. /// internal static string _008_StopRecursingMapping_Fixed { get { @@ -494,8 +493,8 @@ internal static string _009_IdentityFunctionMapping { /// return new UserDTO() /// { /// Age = old.Age, - /// Debs = old.Debs.Select(oldDeb => oldDeb.Clone() as AccountDTO).ToList(), - /// Source = new UserSourceDTO(providerName: old.Source.ProviderName, providerAddress [rest of string was truncated]";. + /// Debs = old.Debs.ConvertAll(oldDeb => oldDeb.Clone() as AccountDTO), + /// Source = new UserSourceDTO(providerName: old.Source.ProviderName, providerAddress: old [rest of string was truncated]";. /// internal static string _009_IdentityFunctionMapping_FIXED { get { @@ -590,11 +589,11 @@ internal static string _011_IdentityFunctionMappingForCollection { /// { /// public static List<UserDTO> Map(List<UserDTO> old) /// { - /// return old.Select(oldElement => new UserDTO() + /// return old.ConvertAll(oldElement => new UserDTO() /// { /// Age = oldElement.Age, - /// Debs = oldElement.Debs.Select(oldElementDeb => oldElementDeb.Clone() as AccountDTO).ToList(), - /// Source = new Use [rest of string was truncated]";. + /// Debs = oldElement.Debs.ConvertAll(oldElementDeb => oldElementDeb.Clone() as AccountDTO), + /// Source = new User [rest of string was truncated]";. /// internal static string _011_IdentityFunctionMappingForCollection_FIXED { get { @@ -658,8 +657,8 @@ internal static string _012_CollectionMappingWithSingularLambdaParameterName { /// /// public static List<YY> Map(List<XX> categories) /// { - /// return categories.Select(category => new YY() - /// [rest of string was truncated]";. + /// return categories.ConvertAll(category => new YY() + /// [rest of string was truncated]";. /// internal static string _012_CollectionMappingWithSingularLambdaParameterName_FIXED { get { @@ -919,9 +918,8 @@ internal static string _016_CollectionMappingWithIrregularSingularLambdaParamete /// /// public static List<YY> Map(List<XX> people) /// { - /// return people.Select(person => new YY() - /// { - /// [rest of string was truncated]";. + /// return people.ConvertAll(person => new YY() + /// [rest of string was truncated]";. /// internal static string _016_CollectionMappingWithIrregularSingularLambdaParameterName_FIXED { get { @@ -985,7 +983,7 @@ internal static string _017_CollectionMappingWithIrregularCamelCaseSingularLambd /// /// public static List<YY> Map(List<XX> relatedPeople) /// { - /// return relatedPeople.Select(relatedPerson => new Y [rest of string was truncated]";. + /// return relatedPeople.ConvertAll(relatedPerson => n [rest of string was truncated]";. /// internal static string _017_CollectionMappingWithIrregularCamelCaseSingularLambdaParameterName_FIXED { get { @@ -1176,19 +1174,17 @@ internal static string _020_MappingPropertiesInConstructorInheritedFromLibraryCl ///{ /// public class TestMapper /// { - /// public static UserDTO Map(string firstName, string lastName) + /// public static UserDTO [|Map|](string firstName, string lastName) /// { - /// return new UserDTO - /// { - /// FirstName = firstName, - /// LastName = lastName - /// }; + /// throw new NotImplementedException(); /// } /// } /// /// public class UserDTO /// { - /// public string First [rest of string was truncated]";. + /// public string FirstName { get; set;} + /// public string LastName { get; set; } + /// public int [rest of string was truncated]";. /// internal static string _021_MultiParameterPureMappingMethod { get { @@ -1206,22 +1202,89 @@ internal static string _021_MultiParameterPureMappingMethod { ///{ /// public class TestMapper /// { - /// public static UserDTO [|Map|](string firstName, string lastName) + /// public static UserDTO Map(string firstName, string lastName) /// { - /// throw new NotImplementedException(); + /// return new UserDTO() + /// { + /// FirstName = firstName, + /// LastName = lastName + /// }; /// } /// } /// /// public class UserDTO /// { - /// public string FirstName { get; } - /// public string LastName { get; private set; } - /// public [rest of string was truncated]";. + /// public string F [rest of string was truncated]";. /// internal static string _021_MultiParameterPureMappingMethod_FIxed { get { return ResourceManager.GetString("_021_MultiParameterPureMappingMethod_FIxed", resourceCulture); } } + + /// + /// Looks up a localized string similar to using System; + ///using System.Collections.Generic; + ///using System.Linq; + /// + ///namespace TestAutoMapper.Identity.X + ///{ + /// public class XX + /// { + /// public int Id { get; set; } + /// public string Name { get; set; } + /// } + /// + /// public class YY + /// { + /// public int Id { get; set; } + /// public string Name { get; set; } + /// } + /// + /// public static class Mapper{ + /// + /// public static List<YY> [|Map|](IList<XX> categories) + /// { + /// throw new NotImplementedException() + /// } + /// [rest of string was truncated]";. + /// + internal static string _022_CollectionMappingIListToList { + get { + return ResourceManager.GetString("_022_CollectionMappingIListToList", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to using System; + ///using System.Collections.Generic; + ///using System.Linq; + /// + ///namespace TestAutoMapper.Identity.X + ///{ + /// public class XX + /// { + /// public int Id { get; set; } + /// public string Name { get; set; } + /// } + /// + /// public class YY + /// { + /// public int Id { get; set; } + /// public string Name { get; set; } + /// } + /// + /// public static class Mapper{ + /// + /// public static List<YY> Map(IList<XX> categories) + /// { + /// return categories.Select(category => new YY() + /// [rest of string was truncated]";. + /// + internal static string _022_CollectionMappingIListToList_Fixed { + get { + return ResourceManager.GetString("_022_CollectionMappingIListToList_Fixed", resourceCulture); + } + } } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.resx b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.resx index 89fe786..c4dd11e 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.resx +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTestCases.resx @@ -244,4 +244,10 @@ TestCaseData\021_MultiParameterPureMappingMethod_FIxed.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + TestCaseData\022_CollectionMappingIListToList.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + + + TestCaseData\022_CollectionMappingIListToList_Fixed.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8 + \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTests.cs b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTests.cs index 74d284a..d20211f 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTests.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/MappingGeneratorTests.cs @@ -140,6 +140,12 @@ public void should_be_able_to_implement_multi_parameter_pure_method() TestCodeRefactoring(_021_MultiParameterPureMappingMethod, _021_MultiParameterPureMappingMethod_FIxed); } + [Test] + public void should_be_able_to_map_IList_to_List_using_linq() + { + TestCodeRefactoring(_022_CollectionMappingIListToList, _022_CollectionMappingIListToList_Fixed); + } + protected override string LanguageName => LanguageNames.CSharp; protected override CodeRefactoringProvider CreateProvider() diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod_FIXED.txt index b284e9d..9af75ef 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/001_PureMappingMethod_FIXED.txt @@ -12,11 +12,11 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData return new UserDTO() { Age = entity.Age, - Debs = entity.Debs.Select(entityDeb => new AccountDTO() + Debs = entity.Debs.ConvertAll(entityDeb => new AccountDTO() { BankName = entityDeb.BankName, Number = entityDeb.Number - }).ToList(), + }), Source = new UserSourceDTO(providerName: entity.Source.ProviderName, providerAddress: entity.Source.ProviderAddress), ImageData = entity.ImageData, LuckyNumbers = entity.LuckyNumbers, @@ -29,14 +29,14 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData FlatNo = entity.MainAddress.FlatNo, BuildingNo = entity.MainAddress.BuildingNo }, - Addresses = entity.Addresses.Select(entityAddress => new AddressDTO() + Addresses = entity.Addresses.ConvertAll(entityAddress => new AddressDTO() { City = entityAddress.City, ZipCode = entityAddress.ZipCode, Street = entityAddress.Street, FlatNo = entityAddress.FlatNo, BuildingNo = entityAddress.BuildingNo - }).ToList().AsReadOnly(), + }).AsReadOnly(), UnitId = entity.Unit.Id, ExtraSavings = entity.ExtraSavings.Value }; diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/002_PureMappingMethodWithGenerics.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/002_PureMappingMethodWithGenerics.txt index 9160a79..8f6b693 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/002_PureMappingMethodWithGenerics.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/002_PureMappingMethodWithGenerics.txt @@ -75,7 +75,7 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData public List LuckyNumbers { get; set; } public AddressEntity MainAddress { get; set; } public string AddressCity { get; set; } - public List Addresses { get; set; } + public IList Addresses { get; set; } public UnitEntity Unit { get; set; } public int GetTotal() diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/002_PureMappingMethodWithGenerics_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/002_PureMappingMethodWithGenerics_FIXED.txt index fe62d5a..b2cc177 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/002_PureMappingMethodWithGenerics_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/002_PureMappingMethodWithGenerics_FIXED.txt @@ -12,11 +12,11 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData return new TDto() { Age = entity.Age, - Debs = entity.Debs.Select(entityDeb => new AccountDTO() + Debs = entity.Debs.ConvertAll(entityDeb => new AccountDTO() { BankName = entityDeb.BankName, Number = entityDeb.Number - }).ToList(), + }), Source = new UserSourceDTO(providerName: entity.Source.ProviderName, providerAddress: entity.Source.ProviderAddress), ImageData = entity.ImageData, LuckyNumbers = entity.LuckyNumbers, @@ -104,7 +104,7 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData public List LuckyNumbers { get; set; } public AddressEntity MainAddress { get; set; } public string AddressCity { get; set; } - public List Addresses { get; set; } + public IList Addresses { get; set; } public UnitEntity Unit { get; set; } public int GetTotal() diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/003_MappingFromOneToAnotherParameter_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/003_MappingFromOneToAnotherParameter_FIXED.txt index 7b9b680..b915c5e 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/003_MappingFromOneToAnotherParameter_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/003_MappingFromOneToAnotherParameter_FIXED.txt @@ -10,11 +10,11 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData public static void Map(UserEntity src, UserDTO dst) { dst.Age = src.Age; - dst.Debs = src.Debs.Select(srcDeb => new AccountDTO() + dst.Debs = src.Debs.ConvertAll(srcDeb => new AccountDTO() { BankName = srcDeb.BankName, Number = srcDeb.Number - }).ToList(); + }); dst.Source = new UserSourceDTO(providerName: src.Source.ProviderName, providerAddress: src.Source.ProviderAddress); dst.ImageData = src.ImageData; dst.LuckyNumbers = src.LuckyNumbers; @@ -27,14 +27,14 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData FlatNo = src.MainAddress.FlatNo, BuildingNo = src.MainAddress.BuildingNo }; - dst.Addresses = src.Addresses.Select(srcAddress => new AddressDTO() + dst.Addresses = src.Addresses.ConvertAll(srcAddress => new AddressDTO() { City = srcAddress.City, ZipCode = srcAddress.ZipCode, Street = srcAddress.Street, FlatNo = srcAddress.FlatNo, BuildingNo = srcAddress.BuildingNo - }).ToList().AsReadOnly(); + }).AsReadOnly(); dst.UnitId = src.Unit.Id; } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/004_UpdateThisObjectWithSingleParameter.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/004_UpdateThisObjectWithSingleParameter.txt index 2b3df83..92bb662 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/004_UpdateThisObjectWithSingleParameter.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/004_UpdateThisObjectWithSingleParameter.txt @@ -72,7 +72,7 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData public List LuckyNumbers { get; set; } public AddressEntity MainAddress { get; set; } public string AddressCity { get; set; } - public List Addresses { get; set; } + public IList Addresses { get; set; } public UnitEntity Unit { get; set; } public int GetTotal() diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/004_UpdateThisObjectWithSingleParameter_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/004_UpdateThisObjectWithSingleParameter_FIXED.txt index c09bbc0..758cf55 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/004_UpdateThisObjectWithSingleParameter_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/004_UpdateThisObjectWithSingleParameter_FIXED.txt @@ -31,11 +31,11 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData BankName = entity.Account.BankName, Number = entity.Account.Number }; - Debs = entity.Debs.Select(entityDeb => new AccountDTO() + Debs = entity.Debs.ConvertAll(entityDeb => new AccountDTO() { BankName = entityDeb.BankName, Number = entityDeb.Number - }).ToList(); + }); Source = new UserSourceDTO(providerName: entity.Source.ProviderName, providerAddress: entity.Source.ProviderAddress); ImageData = entity.ImageData; LuckyNumbers = entity.LuckyNumbers; @@ -104,7 +104,7 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData public List LuckyNumbers { get; set; } public AddressEntity MainAddress { get; set; } public string AddressCity { get; set; } - public List Addresses { get; set; } + public IList Addresses { get; set; } public UnitEntity Unit { get; set; } public int GetTotal() diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/006_ConstructorWithSingleParameter_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/006_ConstructorWithSingleParameter_FIXED.txt index e63599a..6ac1207 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/006_ConstructorWithSingleParameter_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/006_ConstructorWithSingleParameter_FIXED.txt @@ -33,11 +33,11 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData BankName = entity.Account.BankName, Number = entity.Account.Number }; - Debs = entity.Debs.Select(entityDeb => new AccountDTO() + Debs = entity.Debs.ConvertAll(entityDeb => new AccountDTO() { BankName = entityDeb.BankName, Number = entityDeb.Number - }).ToList(); + }); Source = new UserSourceDTO(providerName: entity.Source.ProviderName, providerAddress: entity.Source.ProviderAddress); ImageData = entity.ImageData; LuckyNumbers = entity.LuckyNumbers; @@ -50,14 +50,14 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData FlatNo = entity.MainAddress.FlatNo, BuildingNo = entity.MainAddress.BuildingNo }; - Addresses = entity.Addresses.Select(entityAddress => new AddressDTO() + Addresses = entity.Addresses.ConvertAll(entityAddress => new AddressDTO() { City = entityAddress.City, ZipCode = entityAddress.ZipCode, Street = entityAddress.Street, FlatNo = entityAddress.FlatNo, BuildingNo = entityAddress.BuildingNo - }).ToList().AsReadOnly(); + }).AsReadOnly(); UnitId = entity.Unit.Id; } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/008_StopRecursingMapping_Fixed.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/008_StopRecursingMapping_Fixed.txt index ebfd38b..a70ae34 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/008_StopRecursingMapping_Fixed.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/008_StopRecursingMapping_Fixed.txt @@ -13,12 +13,12 @@ namespace MappingGenerator.Test.MappingGenerator.TestCaseData return new Model1Vm() { Id = src.Id, - Model2s = src.Model2s.Select(srcModel2 => new Model2Vm() + Model2s = src.Model2s.ConvertAll(srcModel2 => new Model2Vm() { Id = srcModel2.Id, Model1 = srcModel2.Model1 /* Stop recursive mapping */, Label = srcModel2.Label - }).ToList() + }) }; } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/009_IdentityFunctionMapping_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/009_IdentityFunctionMapping_FIXED.txt index 470cc24..439064d 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/009_IdentityFunctionMapping_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/009_IdentityFunctionMapping_FIXED.txt @@ -12,7 +12,7 @@ namespace TestAutoMapper.Identity return new UserDTO() { Age = old.Age, - Debs = old.Debs.Select(oldDeb => oldDeb.Clone() as AccountDTO).ToList(), + Debs = old.Debs.ConvertAll(oldDeb => oldDeb.Clone() as AccountDTO), Source = new UserSourceDTO(providerName: old.Source.ProviderName, providerAddress: old.Source.ProviderAddress), Login = old.Login, ImageData = old.ImageData.ToArray(), diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/011_IdentityFunctionMappingForCollection_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/011_IdentityFunctionMappingForCollection_FIXED.txt index ea93c50..2b9784f 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/011_IdentityFunctionMappingForCollection_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/011_IdentityFunctionMappingForCollection_FIXED.txt @@ -9,10 +9,10 @@ namespace TestAutoMapper.Identity { public static List Map(List old) { - return old.Select(oldElement => new UserDTO() + return old.ConvertAll(oldElement => new UserDTO() { Age = oldElement.Age, - Debs = oldElement.Debs.Select(oldElementDeb => oldElementDeb.Clone() as AccountDTO).ToList(), + Debs = oldElement.Debs.ConvertAll(oldElementDeb => oldElementDeb.Clone() as AccountDTO), Source = new UserSourceDTO(providerName: oldElement.Source.ProviderName, providerAddress: oldElement.Source.ProviderAddress), Login = oldElement.Login, ImageData = oldElement.ImageData.ToArray(), @@ -35,7 +35,7 @@ namespace TestAutoMapper.Identity BuildingNo = oldElementAddress.BuildingNo }).ToList().AsReadOnly(), UnitId = oldElement.UnitId - }).ToList(); + }); } } diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/012_CollectionMappingWithSingularLambdaParameterName_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/012_CollectionMappingWithSingularLambdaParameterName_FIXED.txt index 75be809..850a244 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/012_CollectionMappingWithSingularLambdaParameterName_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/012_CollectionMappingWithSingularLambdaParameterName_FIXED.txt @@ -20,11 +20,11 @@ namespace TestAutoMapper.Identity.X public static List Map(List categories) { - return categories.Select(category => new YY() + return categories.ConvertAll(category => new YY() { Id = category.Id, Name = category.Name - }).ToList(); + }); } } } \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/013_CollectionMappingWithPrefixedLambdaParameterName_FIXED..txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/013_CollectionMappingWithPrefixedLambdaParameterName_FIXED..txt index 8d3eea5..d28407a 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/013_CollectionMappingWithPrefixedLambdaParameterName_FIXED..txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/013_CollectionMappingWithPrefixedLambdaParameterName_FIXED..txt @@ -21,11 +21,11 @@ namespace TestAutoMapper.Identity.X public static List MapNew(List categories) { - return categories.Select(category => new ZZ() + return categories.ConvertAll(category => new ZZ() { CategoryId = category.Id, CategoryName = category.Name - }).ToList(); + }); } } } \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/014_CollectionMappingWithGenericName_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/014_CollectionMappingWithGenericName_FIXED.txt index 7612235..8899c40 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/014_CollectionMappingWithGenericName_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/014_CollectionMappingWithGenericName_FIXED.txt @@ -21,11 +21,11 @@ namespace TestAutoMapper.Identity.X public static List MapNew(List dictionary) { - return dictionary.Select(item => new ZZ() + return dictionary.ConvertAll(item => new ZZ() { Id = item.Id, Name = item.Name - }).ToList(); + }); } } } \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/015_CollectionMappingWithPostfixGenericName_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/015_CollectionMappingWithPostfixGenericName_FIXED.txt index fa24fff..4cda2ed 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/015_CollectionMappingWithPostfixGenericName_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/015_CollectionMappingWithPostfixGenericName_FIXED.txt @@ -21,11 +21,11 @@ namespace TestAutoMapper.Identity.X public static List MapNew(List usersList) { - return usersList.Select(user => new ZZ() + return usersList.ConvertAll(user => new ZZ() { Id = user.Id, Name = user.Name - }).ToList(); + }); } } } \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/016_CollectionMappingWithIrregularSingularLambdaParameterName_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/016_CollectionMappingWithIrregularSingularLambdaParameterName_FIXED.txt index b36a919..639a03e 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/016_CollectionMappingWithIrregularSingularLambdaParameterName_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/016_CollectionMappingWithIrregularSingularLambdaParameterName_FIXED.txt @@ -20,11 +20,11 @@ namespace TestAutoMapper.Identity.X public static List Map(List people) { - return people.Select(person => new YY() + return people.ConvertAll(person => new YY() { Id = person.Id, Name = person.Name - }).ToList(); + }); } } } \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/017_CollectionMappingWithIrregularCamelCaseSingularLambdaParameterName_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/017_CollectionMappingWithIrregularCamelCaseSingularLambdaParameterName_FIXED.txt index f5fa345..b1d4f21 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/017_CollectionMappingWithIrregularCamelCaseSingularLambdaParameterName_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/017_CollectionMappingWithIrregularCamelCaseSingularLambdaParameterName_FIXED.txt @@ -20,11 +20,11 @@ namespace TestAutoMapper.Identity.X public static List Map(List relatedPeople) { - return relatedPeople.Select(relatedPerson => new YY() + return relatedPeople.ConvertAll(relatedPerson => new YY() { Id = relatedPerson.Id, Name = relatedPerson.Name - }).ToList(); + }); } } } \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/018_CollectionMappingWithPostfixGenericNameInSingular_FIXED.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/018_CollectionMappingWithPostfixGenericNameInSingular_FIXED.txt index 82a9732..75a8635 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/018_CollectionMappingWithPostfixGenericNameInSingular_FIXED.txt +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/018_CollectionMappingWithPostfixGenericNameInSingular_FIXED.txt @@ -21,11 +21,11 @@ namespace TestAutoMapper.Identity.X public static List MapNew(List userList) { - return userList.Select(user => new ZZ() + return userList.ConvertAll(user => new ZZ() { Id = user.Id, Name = user.Name - }).ToList(); + }); } } } \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/022_CollectionMappingIListToList.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/022_CollectionMappingIListToList.txt new file mode 100644 index 0000000..39f2ca6 --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/022_CollectionMappingIListToList.txt @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace TestAutoMapper.Identity.X +{ + public class XX + { + public int Id { get; set; } + public string Name { get; set; } + } + + public class YY + { + public int Id { get; set; } + public string Name { get; set; } + } + + public static class Mapper{ + + public static List [|Map|](IList categories) + { + throw new NotImplementedException() + } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/022_CollectionMappingIListToList_Fixed.txt b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/022_CollectionMappingIListToList_Fixed.txt new file mode 100644 index 0000000..d323640 --- /dev/null +++ b/MappingGenerator/MappingGenerator/MappingGenerator.Test/MappingGenerator/TestCaseData/022_CollectionMappingIListToList_Fixed.txt @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace TestAutoMapper.Identity.X +{ + public class XX + { + public int Id { get; set; } + public string Name { get; set; } + } + + public class YY + { + public int Id { get; set; } + public string Name { get; set; } + } + + public static class Mapper{ + + public static List Map(IList categories) + { + return categories.Select(category => new YY() + { + Id = category.Id, + Name = category.Name + }).ToList(); + } + } +} \ No newline at end of file diff --git a/MappingGenerator/MappingGenerator/MappingGenerator/MappingEngine.cs b/MappingGenerator/MappingGenerator/MappingGenerator/MappingEngine.cs index 05a3c90..bfee13d 100644 --- a/MappingGenerator/MappingGenerator/MappingGenerator/MappingEngine.cs +++ b/MappingGenerator/MappingGenerator/MappingGenerator/MappingEngine.cs @@ -268,11 +268,12 @@ private SyntaxNode MapCollections(SyntaxNode sourceAccess, ITypeSymbol sourceLis var targetListElementType = MappingHelper.GetElementType(targetListType); if (ShouldCreateConversionBetweenTypes(targetListElementType, sourceListElementType)) { - var selectAccess = syntaxGenerator.MemberAccessExpression(sourceAccess, "Select"); + var useConvert = CanUseConvert(sourceListType); + var selectAccess = useConvert ? syntaxGenerator.MemberAccessExpression(sourceAccess, "ConvertAll"): syntaxGenerator.MemberAccessExpression(sourceAccess, "Select"); var lambdaParameterName = NameHelper.CreateLambdaParameterName(sourceAccess); var mappingLambda = CreateMappingLambda(lambdaParameterName, sourceListElementType, targetListElementType, mappingPath); var selectInvocation = syntaxGenerator.InvocationExpression(selectAccess, mappingLambda); - var toList = AddMaterializeCollectionInvocation(syntaxGenerator, selectInvocation, targetListType); + var toList = useConvert? selectInvocation: AddMaterializeCollectionInvocation(syntaxGenerator, selectInvocation, targetListType); return MappingHelper.WrapInReadonlyCollectionIfNecessary(toList, isReadonlyCollection, syntaxGenerator); } @@ -280,6 +281,11 @@ private SyntaxNode MapCollections(SyntaxNode sourceAccess, ITypeSymbol sourceLis return MappingHelper.WrapInReadonlyCollectionIfNecessary(toListInvocation, isReadonlyCollection, syntaxGenerator); } + private bool CanUseConvert(ITypeSymbol sourceListType) + { + return sourceListType.Name == "List" && sourceListType.GetMembers("ConvertAll").Length != 0; + } + public SyntaxNode CreateMappingLambda(string lambdaParameterName, ITypeSymbol sourceListElementType, ITypeSymbol targetListElementType, MappingPath mappingPath) { var listElementMappingStm = MapExpression(new MappingElement() diff --git a/README.md b/README.md index 76a53c7..3a5d1ae 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ CS7036 There is no argument given that corresponds to the required formal parame - Complete empty initialization block in lambda expression `Expression> = (T) => new T2{}` ![initialization block in lambda expression](https://user-images.githubusercontent.com/7759991/41869113-4704c6f0-78b8-11e8-8c3c-47a6b5bf308c.gif) -- Provide local accessoble variables as parameters for method and constructor invocation +- Provide local accessible variables as parameters for method and constructor invocation ![locals as parameters](doc/localsforconstructor.gif) - Create missing mapping lambda