Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: added snapshot testing for generated code #1753

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions Refit.Tests/InterfaceStubGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Collections.Immutable;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Testing;
Expand Down
19 changes: 19 additions & 0 deletions Refit.sln
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Refit.Xml", "Refit.Xml\Refi
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Refit.Benchmarks", "Refit.Benchmarks\Refit.Benchmarks.csproj", "{ABD72A27-9C30-481A-8303-D8F825A8FD47}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RefitGenerator.Tests", "RefitGenerator.Tests\RefitGenerator.Tests.csproj", "{10790A5E-8FB6-451B-BCBC-8F641973F22C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -174,13 +176,30 @@ Global
{ABD72A27-9C30-481A-8303-D8F825A8FD47}.Release|x64.Build.0 = Release|Any CPU
{ABD72A27-9C30-481A-8303-D8F825A8FD47}.Release|x86.ActiveCfg = Release|Any CPU
{ABD72A27-9C30-481A-8303-D8F825A8FD47}.Release|x86.Build.0 = Release|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Debug|ARM.ActiveCfg = Debug|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Debug|ARM.Build.0 = Debug|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Debug|x64.ActiveCfg = Debug|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Debug|x64.Build.0 = Debug|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Debug|x86.ActiveCfg = Debug|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Debug|x86.Build.0 = Debug|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Release|Any CPU.Build.0 = Release|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Release|ARM.ActiveCfg = Release|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Release|ARM.Build.0 = Release|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Release|x64.ActiveCfg = Release|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Release|x64.Build.0 = Release|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Release|x86.ActiveCfg = Release|Any CPU
{10790A5E-8FB6-451B-BCBC-8F641973F22C}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{EB833B36-D3CA-4308-A776-8D574F2ADF64} = {0E99249A-FB80-4C60-8FD3-13820E853FF7}
{ABD72A27-9C30-481A-8303-D8F825A8FD47} = {0E99249A-FB80-4C60-8FD3-13820E853FF7}
{10790A5E-8FB6-451B-BCBC-8F641973F22C} = {0E99249A-FB80-4C60-8FD3-13820E853FF7}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6E9C2873-AFF9-4D32-A784-1BA094814054}
Expand Down
16 changes: 16 additions & 0 deletions RefitGenerator.Tests/BaseTestClass.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.Runtime.CompilerServices;

namespace RefitGenerator.Tests;

public class BaseTestClass
{
static BaseTestClass()
{
Verifier.DerivePathInfo(
(file, _, type, method) => new(Path.Combine(Path.GetDirectoryName(file), "_snapshots"), type.Name, method.Name)
);

VerifySourceGenerators.Initialize();
VerifyDiffPlex.Initialize(VerifyTests.DiffPlex.OutputType.Compact);
}
}
108 changes: 108 additions & 0 deletions RefitGenerator.Tests/Fixture.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
using System.Net.Http;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

using Refit;
using Refit.Generator;

namespace RefitGenerator.Tests;


public static class Fixture
{
private const string MainTestFile = "Refit.Tests";

static readonly MetadataReference RefitAssembly = MetadataReference.CreateFromFile(
typeof(GetAttribute).Assembly.Location,
documentation: XmlDocumentationProvider.CreateFromFile(
Path.ChangeExtension(typeof(GetAttribute).Assembly.Location, ".xml")
)
);

private static readonly Type[] ImportantAssemblies = new[]
{
typeof(Binder),
typeof(GetAttribute),
typeof(System.Reactive.Unit),
typeof(Enumerable),
typeof(Newtonsoft.Json.JsonConvert),
typeof(FactAttribute),
typeof(HttpContent),
// typeof(ModelObject),
typeof(Attribute)
};

public static Assembly[] AssemblyReferencesForCodegen =>
AppDomain.CurrentDomain
.GetAssemblies()
.Concat(ImportantAssemblies.Select(x=>x.Assembly))
.Distinct()
.Where(a => !a.IsDynamic)
.ToArray();

public static Compilation CreateLibrary(params string[] source)
{
var references = new List<MetadataReference>();
var assemblies = AssemblyReferencesForCodegen;
foreach (var assembly in assemblies)
{
if (!assembly.IsDynamic)
{
references.Add(MetadataReference.CreateFromFile(assembly.Location));
}
}

references.Add(RefitAssembly);
var compilation = CSharpCompilation.Create(
"compilation",
source.Select(s => CSharpSyntaxTree.ParseText(s)),
references,
new CSharpCompilationOptions(OutputKind.ConsoleApplication)
);

return compilation;
}

public static Task VerifyGenerator(string source)
{
var compilation = CreateLibrary(source);

var generator = new InterfaceStubGenerator();
var driver = CSharpGeneratorDriver.Create(generator);

var ranDriver = driver.RunGenerators(compilation);
var verify = VerifyXunit.Verifier.Verify(ranDriver);
return verify.ToTask();
}

public static async Task<string> GetFileFromRefitTest(string file)
{
#if NET481
return File.ReadAllText(GetRefitTestPath(file));
#else
return await File.ReadAllTextAsync(GetRefitTestPath(file)).ConfigureAwait(false);
#endif
}

private static string GetRefitTestPath(params string[] paths)
{
var ret = GetIntegrationTestRootDirectory();
var start = ret.Split('\\');
// ReSharper disable once UseIndexFromEndExpression
start[start.Length - 1] = MainTestFile;
ret = string.Join("\\", start);
return (new FileInfo(paths.Aggregate(ret, Path.Combine))).FullName;
}

private static string GetIntegrationTestRootDirectory([CallerFilePath] string filePath = default)
{
// XXX: This is an evil hack, but it's okay for a unit test
// We can't use Assembly.Location because unit test runners love
// to move stuff to temp directories
var di = new DirectoryInfo(Path.Combine(Path.GetDirectoryName(filePath)));

return di.FullName;
}
}
46 changes: 46 additions & 0 deletions RefitGenerator.Tests/RefitGenerator.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<Project Sdk="Microsoft.NET.Sdk">

<Import Project="..\Refit\targets\refit.props" />

<PropertyGroup>
<TargetFrameworks>net481;net6.0;net8.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<NoWarn>$(NoWarn);CS1591;CA1819;CA2000;CA2007;CA1056;CA1707;CA1861;xUnit1031</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0"/>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0"/>
<PackageReference Include="xunit" Version="2.5.3"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3"/>
<PackageReference Include="System.Collections.Immutable" Version="9.0.0-preview.5.24306.7" />
<PackageReference Include="Verify.DiffPlex" Version="2.3.0" />
<PackageReference Include="Verify.SourceGenerators" Version="2.2.0" />
<PackageReference Include="Verify.Xunit" Version="22.1.4" />
<PackageReference Include="System.Reactive" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.9.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.SourceGenerators.Testing" Version="1.1.2-beta1.24314.1" />
<ProjectReference Include="..\Refit.Newtonsoft.Json\Refit.Newtonsoft.Json.csproj" />
<ProjectReference Include="..\Refit.Xml\Refit.Xml.csproj" />
<ProjectReference Include="..\InterfaceStubGenerator.Roslyn38\InterfaceStubGenerator.Roslyn38.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="true" />
<ProjectReference Include="..\InterfaceStubGenerator.Roslyn40\InterfaceStubGenerator.Roslyn40.csproj" />
<ProjectReference Include="..\Refit\Refit.csproj" />
</ItemGroup>

<ItemGroup>
<None Include="..\RefitGenerator.Tests\_snapshots\**">
<Link>%(RecursiveDir)\resources\%(Filename)%(Extension)</Link>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<Using Include="Xunit"/>
</ItemGroup>

<ItemGroup>
<Folder Include="_snapshots\" />
</ItemGroup>
</Project>
26 changes: 26 additions & 0 deletions RefitGenerator.Tests/RefitGeneratorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace RefitGenerator.Tests;

[UsesVerify]
public class RefitGeneratorTests : BaseTestClass
{
[Fact]
public async Task NoRefitInterfacesSmokeTest()
{
var input = await Fixture.GetFileFromRefitTest("IInterfaceWithoutRefit.cs");
await Fixture.VerifyGenerator(input);
}

[Fact]
public async Task FindInterfacesSmokeTest()
{
var input = await Fixture.GetFileFromRefitTest("GitHubApi.cs");
await Fixture.VerifyGenerator(input);
}

[Fact]
public async Task GenerateInterfaceStubsWithoutNamespaceSmokeTest()
{
var input = await Fixture.GetFileFromRefitTest("IServiceWithoutNamespace.cs");
await Fixture.VerifyGenerator(input);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//HintName: Generated.g.cs

#pragma warning disable
namespace Refit.Implementation
{

/// <inheritdoc />
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::System.Diagnostics.DebuggerNonUserCode]
[global::RefitInternalGenerated.PreserveAttribute]
[global::System.Reflection.Obfuscation(Exclude=true)]
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal static partial class Generated
{
#if NET5_0_OR_GREATER
[System.Runtime.CompilerServices.ModuleInitializer]
[System.Diagnostics.CodeAnalysis.DynamicDependency(System.Diagnostics.CodeAnalysis.DynamicallyAccessedMemberTypes.All, typeof(global::Refit.Implementation.Generated))]
public static void Initialize()
{
}
#endif
}
}
#pragma warning restore
Loading
Loading