Skip to content

Commit

Permalink
improve tests
Browse files Browse the repository at this point in the history
  • Loading branch information
pwelter34 committed Nov 13, 2023
1 parent 6b17416 commit 703098c
Show file tree
Hide file tree
Showing 12 changed files with 340 additions and 33 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -396,3 +396,6 @@ FodyWeavers.xsd

# JetBrains Rider
*.sln.iml

# Verify
*.received.txt
5 changes: 3 additions & 2 deletions Backgrounder.sln
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Backgrounder.Generators", "
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Build", "Build", "{1AA0FC81-4621-47EC-9D4F-B64662B68CC8}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
src\Directory.Build.props = src\Directory.Build.props
.github\workflows\dotnet.yml = .github\workflows\dotnet.yml
README.md = README.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Backgrounder.Generators.Tests", "test\Backgrounder.Generators.Tests\Backgrounder.Generators.Tests.csproj", "{5688BE7D-01D0-4DAE-96B3-CD2D68739B83}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Backgrounder.Generators.Tests", "test\Backgrounder.Generators.Tests\Backgrounder.Generators.Tests.csproj", "{5688BE7D-01D0-4DAE-96B3-CD2D68739B83}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Backgrounder.Sample.Library", "samples\Backgrounder.Sample.Library\Backgrounder.Sample.Library.csproj", "{098517FD-EFBF-4B60-976B-DF26D5BA4493}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Backgrounder.Sample.Library", "samples\Backgrounder.Sample.Library\Backgrounder.Sample.Library.csproj", "{098517FD-EFBF-4B60-976B-DF26D5BA4493}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
166 changes: 166 additions & 0 deletions test/Backgrounder.Generators.Tests/BackgroundGeneratorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
using System.Collections.Immutable;

using FluentAssertions;

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace Backgrounder.Generators.Tests;

[UsesVerify]
public class BackgroundGeneratorTests
{
[Fact]
public Task GenerateSingleParameter()
{
var source = @"
using Backgrounder;
namespace Backgrounder.Sample;
public interface ISampleJob
{
Task DoWork(int? jobId);
}
public class SampleJob : ISampleJob
{
[BackgroundOperation]
public Task DoWork(int? jobId) => Task.FromResult(jobId);
}
";

var (diagnostics, output) = GetGeneratedOutput<BackgroundGenerator>(source);

diagnostics.Should().BeEmpty();

return Verifier
.Verify(output)
.UseDirectory("Snapshots")
.ScrubLinesContaining("GeneratedCodeAttribute");
}

[Fact]
public Task GenerateMultipleParameter()
{
var source = @"
using Backgrounder;
namespace Backgrounder.Sample;
public interface ISampleJob
{
Task DoWork(int jobId, string? name);
}
public class SampleJob : ISampleJob
{
[BackgroundOperation<ISampleJob>]
public Task DoWork(int jobId, string? name) => Task.FromResult(jobId);
}
";

var (diagnostics, output) = GetGeneratedOutput<BackgroundGenerator>(source);

diagnostics.Should().BeEmpty();

return Verifier
.Verify(output)
.UseDirectory("Snapshots")
.ScrubLinesContaining("GeneratedCodeAttribute");
}

[Fact]
public Task GenerateStaticMethod()
{
var source = @"
using Backgrounder;
namespace Backgrounder.Sample;
public class SampleJob
{
[BackgroundOperation]
public static Task StaticWork(int jobId)
{
return Task.FromResult(jobId);
}
}
";

var (diagnostics, output) = GetGeneratedOutput<BackgroundGenerator>(source);

diagnostics.Should().BeEmpty();

return Verifier
.Verify(output)
.UseDirectory("Snapshots")
.ScrubLinesContaining("GeneratedCodeAttribute");
}

[Fact]
public Task GenerateComplexParameter()
{
var source = @"
using Backgrounder;
namespace Backgrounder.Sample;
public interface ISampleJob
{
void CheckPerson(Person person);
}
public class SampleJob : ISampleJob
{
[BackgroundOperation]
public void CheckPerson(Person person) { }
}
public class Person
{
public string? Name { get; set; }
public string? Email { get; set; }
}
";

var (diagnostics, output) = GetGeneratedOutput<BackgroundGenerator>(source);

diagnostics.Should().BeEmpty();

return Verifier
.Verify(output)
.UseDirectory("Snapshots")
.ScrubLinesContaining("GeneratedCodeAttribute");
}

public static (ImmutableArray<Diagnostic> Diagnostics, string Output) GetGeneratedOutput<T>(string source)
where T : IIncrementalGenerator, new()
{
var syntaxTree = CSharpSyntaxTree.ParseText(source);
var references = AppDomain.CurrentDomain.GetAssemblies()
.Where(_ => !_.IsDynamic && !string.IsNullOrWhiteSpace(_.Location))
.Select(_ => MetadataReference.CreateFromFile(_.Location))
.Concat(new[]
{
MetadataReference.CreateFromFile(typeof(T).Assembly.Location),
MetadataReference.CreateFromFile(typeof(BackgroundOperationAttribute).Assembly.Location),
});

var compilation = CSharpCompilation.Create(
"generator",
new[] { syntaxTree },
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

var originalTreeCount = compilation.SyntaxTrees.Length;
var generator = new T();

var driver = CSharpGeneratorDriver.Create(generator);
driver.RunGeneratorsAndUpdateCompilation(compilation, out var outputCompilation, out var diagnostics);

var trees = outputCompilation.SyntaxTrees.ToList();

return (diagnostics, trees.Count != originalTreeCount ? trees[trees.Count - 1].ToString() : string.Empty);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Verify.SourceGenerators" Version="2.2.0" />
<PackageReference Include="Verify.Xunit" Version="22.2.0" />
<PackageReference Include="xunit" Version="2.6.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3">
Expand All @@ -26,6 +32,7 @@

<ItemGroup>
<ProjectReference Include="..\..\src\Backgrounder.Generators\Backgrounder.Generators.csproj" />
<ProjectReference Include="..\..\src\Backgrounder\Backgrounder.csproj" />
</ItemGroup>

</Project>
9 changes: 9 additions & 0 deletions test/Backgrounder.Generators.Tests/ModuleInitialization.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.Runtime.CompilerServices;

namespace Backgrounder.Generators.Tests;

public static class ModuleInitialization
{
[ModuleInitializer]
public static void Initialize() => VerifySourceGenerators.Initialize();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// <auto-generated />
#nullable enable

namespace Backgrounder.Sample
{
/// <summary>
/// Extension methods for Backgrounder
/// </summary>
public static partial class SampleJobCheckPersonExtensions
{
public record CheckPersonMessageDAADBCDB(Backgrounder.Sample.Person person);

/// <summary>
/// Enqueue the method Backgrounder.Sample.SampleJob.CheckPerson(Backgrounder.Sample.Person) for execution in the background
/// </summary>
public static async global::System.Threading.Tasks.Task CheckPerson(this global::Backgrounder.IBackgrounder backgrounder, Backgrounder.Sample.Person person)
{
var methodParameters = new CheckPersonMessageDAADBCDB(person);
await backgrounder.EnqueueAsync("Backgrounder.Sample.SampleJob.CheckPerson(Backgrounder.Sample.Person)", methodParameters);
}

internal static global::System.Threading.Tasks.Task ExecuteCheckPersonDAADBCDB(global::System.IServiceProvider serviceProvider, byte[] messageBody)
{
var messageSerializer = global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::Backgrounder.IMessageSerializer>(serviceProvider);
var methodParameters = messageSerializer.Deserialize<CheckPersonMessageDAADBCDB>(messageBody);
var worker = global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<SampleJob>(serviceProvider);
worker.CheckPerson(methodParameters.person);
return global::System.Threading.Tasks.Task.CompletedTask;
}

[global::System.Runtime.CompilerServices.ModuleInitializerAttribute]
internal static void RegisterCheckPersonDAADBCDB()
{
BackgroundRouter.Register("Backgrounder.Sample.SampleJob.CheckPerson(Backgrounder.Sample.Person)", Backgrounder.Sample.SampleJobCheckPersonExtensions.ExecuteCheckPersonDAADBCDB);
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// <auto-generated />
#nullable enable

namespace Backgrounder.Sample
{
/// <summary>
/// Extension methods for Backgrounder
/// </summary>
public static partial class SampleJobDoWorkExtensions
{
public record DoWorkMessage5A94B72F(int jobId, string? name);

/// <summary>
/// Enqueue the method Backgrounder.Sample.SampleJob.DoWork(int, string?) for execution in the background
/// </summary>
public static async global::System.Threading.Tasks.Task DoWork(this global::Backgrounder.IBackgrounder backgrounder, int jobId, string? name)
{
var methodParameters = new DoWorkMessage5A94B72F(jobId, name);
await backgrounder.EnqueueAsync("Backgrounder.Sample.SampleJob.DoWork(int, string?)", methodParameters);
}

internal static global::System.Threading.Tasks.Task ExecuteDoWork5A94B72F(global::System.IServiceProvider serviceProvider, byte[] messageBody)
{
var messageSerializer = global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::Backgrounder.IMessageSerializer>(serviceProvider);
var methodParameters = messageSerializer.Deserialize<DoWorkMessage5A94B72F>(messageBody);
var worker = global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::Backgrounder.Sample.ISampleJob>(serviceProvider);
worker.DoWork(methodParameters.jobId, methodParameters.name);
return global::System.Threading.Tasks.Task.CompletedTask;
}

[global::System.Runtime.CompilerServices.ModuleInitializerAttribute]
internal static void RegisterDoWork5A94B72F()
{
BackgroundRouter.Register("Backgrounder.Sample.SampleJob.DoWork(int, string?)", Backgrounder.Sample.SampleJobDoWorkExtensions.ExecuteDoWork5A94B72F);
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// <auto-generated />
#nullable enable

namespace Backgrounder.Sample
{
/// <summary>
/// Extension methods for Backgrounder
/// </summary>
public static partial class SampleJobDoWorkExtensions
{
public record DoWorkMessage3299E5EA(int? jobId);

/// <summary>
/// Enqueue the method Backgrounder.Sample.SampleJob.DoWork(int?) for execution in the background
/// </summary>
public static async global::System.Threading.Tasks.Task DoWork(this global::Backgrounder.IBackgrounder backgrounder, int? jobId)
{
var methodParameters = new DoWorkMessage3299E5EA(jobId);
await backgrounder.EnqueueAsync("Backgrounder.Sample.SampleJob.DoWork(int?)", methodParameters);
}

internal static global::System.Threading.Tasks.Task ExecuteDoWork3299E5EA(global::System.IServiceProvider serviceProvider, byte[] messageBody)
{
var messageSerializer = global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::Backgrounder.IMessageSerializer>(serviceProvider);
var methodParameters = messageSerializer.Deserialize<DoWorkMessage3299E5EA>(messageBody);
var worker = global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<SampleJob>(serviceProvider);
worker.DoWork(methodParameters.jobId);
return global::System.Threading.Tasks.Task.CompletedTask;
}

[global::System.Runtime.CompilerServices.ModuleInitializerAttribute]
internal static void RegisterDoWork3299E5EA()
{
BackgroundRouter.Register("Backgrounder.Sample.SampleJob.DoWork(int?)", Backgrounder.Sample.SampleJobDoWorkExtensions.ExecuteDoWork3299E5EA);
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// <auto-generated />
#nullable enable

namespace Backgrounder.Sample
{
/// <summary>
/// Extension methods for Backgrounder
/// </summary>
public static partial class SampleJobStaticWorkExtensions
{
public record StaticWorkMessage34AA9206(int jobId);

/// <summary>
/// Enqueue the method Backgrounder.Sample.SampleJob.StaticWork(int) for execution in the background
/// </summary>
public static async global::System.Threading.Tasks.Task StaticWork(this global::Backgrounder.IBackgrounder backgrounder, int jobId)
{
var methodParameters = new StaticWorkMessage34AA9206(jobId);
await backgrounder.EnqueueAsync("Backgrounder.Sample.SampleJob.StaticWork(int)", methodParameters);
}

internal static global::System.Threading.Tasks.Task ExecuteStaticWork34AA9206(global::System.IServiceProvider serviceProvider, byte[] messageBody)
{
var messageSerializer = global::Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<global::Backgrounder.IMessageSerializer>(serviceProvider);
var methodParameters = messageSerializer.Deserialize<StaticWorkMessage34AA9206>(messageBody);
Backgrounder.Sample.SampleJob.StaticWork(methodParameters.jobId);
return global::System.Threading.Tasks.Task.CompletedTask;
}

[global::System.Runtime.CompilerServices.ModuleInitializerAttribute]
internal static void RegisterStaticWork34AA9206()
{
BackgroundRouter.Register("Backgrounder.Sample.SampleJob.StaticWork(int)", Backgrounder.Sample.SampleJobStaticWorkExtensions.ExecuteStaticWork34AA9206);
}

}
}
Loading

0 comments on commit 703098c

Please sign in to comment.