Skip to content

Commit

Permalink
test setup
Browse files Browse the repository at this point in the history
  • Loading branch information
coronabytes committed Oct 5, 2024
1 parent 1c95761 commit 040467d
Show file tree
Hide file tree
Showing 18 changed files with 184 additions and 190 deletions.
30 changes: 30 additions & 0 deletions Core.ServiceMesh.Tests/Core.ServiceMesh.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</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" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Core.ServiceMesh\Core.ServiceMesh.csproj" />
<ProjectReference Include="..\SampleInterfaces\SampleInterfaces.csproj" />
<ProjectReference Include="..\Core.ServiceMesh.SourceGen\Core.ServiceMesh.SourceGen.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>


<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>

</Project>
47 changes: 47 additions & 0 deletions Core.ServiceMesh.Tests/SomeService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System.Diagnostics;
using System.Numerics;
using Core.ServiceMesh.Abstractions;
using Microsoft.Extensions.Logging;
using SampleInterfaces;

namespace Core.ServiceMesh.Tests;

[ServiceMesh("someservice")]
public class SomeService(ILogger<SomeService> logger) : ISomeService
{
public async ValueTask<string> GetSomeString(int a, string b)
{
logger.LogInformation("test log");
Activity.Current?.AddEvent(new ActivityEvent("test 1"));
await Task.Delay(100);
Activity.Current?.AddEvent(new ActivityEvent("test 2"));
return b + " " + a;
}

public async ValueTask CreateSomeObject()
{
await Task.Delay(100);
logger.LogInformation(nameof(CreateSomeObject));
}

public async ValueTask<T> GenericAdd<T>(T a, T b) where T : INumber<T>
{
await Task.Delay(100);
return a + b;
}

public ValueTask<SampleResponse> Sample(SampleRequest request)
{
return ValueTask.FromResult(new SampleResponse(request.Name + " " + request.Amount));
}

public async IAsyncEnumerable<SampleResponse> StreamingResponse(SampleRequest request)
{
await Task.Delay(100);
yield return new SampleResponse("a");
await Task.Delay(100);
yield return new SampleResponse("b");
await Task.Delay(100);
yield return new SampleResponse("c");
}
}
86 changes: 86 additions & 0 deletions Core.ServiceMesh.Tests/UnitTest1.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
using Core.ServiceMesh.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SampleInterfaces;
using Xunit.Abstractions;

namespace Core.ServiceMesh.Tests;

[CollectionDefinition("UnitTest1", DisableParallelization = true)]
public class UnitTest1(ITestOutputHelper logger) : IAsyncLifetime
{
private readonly CancellationTokenSource _cancellation = new();
private IServiceMesh _mesh;
private IServiceProvider _serviceProvider;
private BackgroundService _worker;

public async Task InitializeAsync()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging();
serviceCollection.AddServiceMesh(options =>
{
options.Prefix = Guid.NewGuid().ToString("N");
options.ConfigureNats = opts => opts with
{
Url = "nats://localhost:4222"
};
options.ConfigureStream = (name, config) => { config.MaxAge = TimeSpan.FromMinutes(10); };
options.InterfaceMode = ServiceInterfaceMode.None;
options.Assemblies = [typeof(ISomeService).Assembly, typeof(SomeService).Assembly];
});

_serviceProvider = serviceCollection.BuildServiceProvider(true);
_mesh = _serviceProvider.GetRequiredService<IServiceMesh>();

_worker = (BackgroundService)_mesh;
await _worker.StartAsync(_cancellation.Token);
}

public async Task DisposeAsync()
{
await _cancellation.CancelAsync();

try
{
await _worker.ExecuteTask!;
}
catch
{
// NOP
}
}

[Fact]
public async Task Test1()
{
var someService = _mesh.CreateProxy<ISomeService>();

var res = await someService.GenericAdd(2, 4);

Assert.Equal(6, res);
}

[Fact]
public async Task Test2()
{
var someService = _mesh.CreateProxy<ISomeService>();

var res = await someService.GenericAdd(6m, 6m);

Assert.Equal(12m, res);
}

[Fact]
public async Task Test3()
{
var someService = _mesh.CreateProxy<ISomeService>();

var list = new List<SampleResponse>();

await foreach (var r in someService.StreamingResponse(new SampleRequest("Bla", 133.7m)))
list.Add(r);

Assert.Equal(3, list.Count);
}
}
10 changes: 5 additions & 5 deletions Core.ServiceMesh.sln
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.ServiceMesh.SourceGen"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.ServiceMesh.SourceGen.Tests", "Core.ServiceMesh.SourceGen.Tests\Core.ServiceMesh.SourceGen.Tests.csproj", "{0A12704F-4653-42B9-B4A5-D31BE66512A4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleAppNuget", "SampleAppNuget\SampleAppNuget.csproj", "{46F1E3ED-4BB2-4C40-B454-263B786C9D96}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.ServiceMesh.Tests", "Core.ServiceMesh.Tests\Core.ServiceMesh.Tests.csproj", "{97B811EA-F1D8-4FCE-8855-00F3E36AE354}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -53,10 +53,10 @@ Global
{0A12704F-4653-42B9-B4A5-D31BE66512A4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A12704F-4653-42B9-B4A5-D31BE66512A4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A12704F-4653-42B9-B4A5-D31BE66512A4}.Release|Any CPU.Build.0 = Release|Any CPU
{46F1E3ED-4BB2-4C40-B454-263B786C9D96}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{46F1E3ED-4BB2-4C40-B454-263B786C9D96}.Debug|Any CPU.Build.0 = Debug|Any CPU
{46F1E3ED-4BB2-4C40-B454-263B786C9D96}.Release|Any CPU.ActiveCfg = Release|Any CPU
{46F1E3ED-4BB2-4C40-B454-263B786C9D96}.Release|Any CPU.Build.0 = Release|Any CPU
{97B811EA-F1D8-4FCE-8855-00F3E36AE354}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{97B811EA-F1D8-4FCE-8855-00F3E36AE354}.Debug|Any CPU.Build.0 = Debug|Any CPU
{97B811EA-F1D8-4FCE-8855-00F3E36AE354}.Release|Any CPU.ActiveCfg = Release|Any CPU
{97B811EA-F1D8-4FCE-8855-00F3E36AE354}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
2 changes: 0 additions & 2 deletions Core.ServiceMesh/Internal/ServiceMeshWorker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,6 @@ public async IAsyncEnumerable<T> StreamAsync<T>(string subject, object[] args, T

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
//RemoteDispatchProxy.Worker = this;

_streamChannel = Channel.CreateBounded<(NatsJSMsg<byte[]>, ConsumerRegistration)>(10);
_broadcastChannel = Channel.CreateBounded<(NatsMsg<byte[]>, ConsumerRegistration)>(10);
_serviceChannel = Channel.CreateBounded<(NatsMsg<byte[]>, ServiceRegistration)>(10);
Expand Down
29 changes: 14 additions & 15 deletions Core.ServiceMesh/ServiceMeshExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Core.ServiceMesh.Internal;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using NATS.Client.Hosting;
using OpenTelemetry.Trace;
Expand All @@ -15,19 +16,19 @@ public static class ServiceMeshExtensions
internal static readonly List<ConsumerRegistration> Consumers = new();
internal static readonly List<ServiceRegistration> Services = new();

public static IHostApplicationBuilder AddServiceMesh(this IHostApplicationBuilder builder,
public static IServiceCollection AddServiceMesh(this IServiceCollection services,
Action<ServiceMeshOptions> configure)
{
var options = new ServiceMeshOptions();
configure(options);

builder.Services.AddNats(options.NatsPoolSize, opts => options.ConfigureNats(opts));
services.AddNats(options.NatsPoolSize, opts => options.ConfigureNats(opts));

builder.Services.AddSingleton(options);
builder.Services.AddSingleton<ServiceMeshWorker>();
builder.Services.AddSingleton<IServiceMesh, ServiceMeshWorker>(sp =>
services.AddSingleton(options);
services.AddSingleton<ServiceMeshWorker>();
services.AddSingleton<IServiceMesh, ServiceMeshWorker>(sp =>
sp.GetRequiredService<ServiceMeshWorker>());
builder.Services.AddSingleton<IHostedService>(sp => sp.GetRequiredService<ServiceMeshWorker>());
services.AddSingleton<IHostedService>(sp => sp.GetRequiredService<ServiceMeshWorker>());

var asms = options.Assemblies.Distinct().ToList();

Expand Down Expand Up @@ -56,7 +57,6 @@ public static IHostApplicationBuilder AddServiceMesh(this IHostApplicationBuilde
}
else
{
// TODO: multiple service implementations?
var itype = type.GetInterfaces().Single();
var attr = itype.GetCustomAttribute<ServiceMeshAttribute>();

Expand Down Expand Up @@ -86,8 +86,7 @@ public static IHostApplicationBuilder AddServiceMesh(this IHostApplicationBuilde
QueueGroup = applyPrefix(attr.Name)!
});

// todo: configurable lifetime
builder.Services.Add(new ServiceDescriptor(type, type, ServiceLifetime.Scoped));
services.Add(new ServiceDescriptor(type, type, ServiceLifetime.Scoped));
}

if (options.InterfaceMode != ServiceInterfaceMode.None)
Expand All @@ -100,7 +99,7 @@ public static IHostApplicationBuilder AddServiceMesh(this IHostApplicationBuilde
var remoteProxy = serviceInterface.Assembly.GetType(serviceInterface.FullName + "RemoteProxy");

if (remoteProxy != null)
builder.Services.AddSingleton(serviceInterface, remoteProxy);
services.AddSingleton(serviceInterface, remoteProxy);
}
else
{
Expand All @@ -109,19 +108,19 @@ public static IHostApplicationBuilder AddServiceMesh(this IHostApplicationBuilde
var remoteProxy = serviceInterface.Assembly.GetType(serviceInterface.FullName + "RemoteProxy");

if (remoteProxy != null)
builder.Services.AddSingleton(serviceInterface, remoteProxy);
services.AddSingleton(serviceInterface, remoteProxy);
}
else if (options.InterfaceMode == ServiceInterfaceMode.AutoTrace)
{
var traceProxy =
serviceInterface.Assembly.GetType(impl.ImplementationType.FullName + "TraceProxy");

if (traceProxy != null)
builder.Services.AddSingleton(serviceInterface, traceProxy);
services.AddSingleton(serviceInterface, traceProxy);
}
else
{
builder.Services.Add(new ServiceDescriptor(serviceInterface, impl.ImplementationType,
services.Add(new ServiceDescriptor(serviceInterface, impl.ImplementationType,
ServiceLifetime.Scoped));
}
}
Expand Down Expand Up @@ -160,7 +159,7 @@ public static IHostApplicationBuilder AddServiceMesh(this IHostApplicationBuilde
var obsolete = consumer.GetCustomAttribute<ObsoleteAttribute>() != null;

if (!obsolete)
builder.Services.Add(new ServiceDescriptor(consumer, consumer, ServiceLifetime.Scoped));
services.Add(new ServiceDescriptor(consumer, consumer, ServiceLifetime.Scoped));

Consumers.Add(new ConsumerRegistration
{
Expand All @@ -177,7 +176,7 @@ public static IHostApplicationBuilder AddServiceMesh(this IHostApplicationBuilde
});
}

return builder;
return services;
}

public static TracerProviderBuilder AddServiceMeshInstrumentation(this TracerProviderBuilder builder)
Expand Down
2 changes: 1 addition & 1 deletion SampleApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

builder.Services.Configure<ObservabilityOptions>(options => { });

builder.AddServiceMesh(options =>
builder.Services.AddServiceMesh(options =>
{
options.Prefix = "dev";
options.ConfigureNats = opts => opts with
Expand Down
32 changes: 0 additions & 32 deletions SampleAppNuget/Controllers/WeatherForecastController.cs

This file was deleted.

14 changes: 0 additions & 14 deletions SampleAppNuget/Mesh/IAnotherService.cs

This file was deleted.

3 changes: 0 additions & 3 deletions SampleAppNuget/Mesh/SampleRequest.cs

This file was deleted.

3 changes: 0 additions & 3 deletions SampleAppNuget/Mesh/SampleResponse.cs

This file was deleted.

25 changes: 0 additions & 25 deletions SampleAppNuget/Program.cs

This file was deleted.

Loading

0 comments on commit 040467d

Please sign in to comment.