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: allow using mockaco on aspnet core apps #89

Merged
merged 1 commit into from
Jun 19, 2022
Merged
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
12 changes: 10 additions & 2 deletions Mockaco.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29102.190
# Visual Studio Version 17
VisualStudioVersion = 17.1.32210.238
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mockaco", "src\Mockaco\Mockaco.csproj", "{8BAA1EC5-0BF5-4DA2-87F7-ED0C7B652517}"
EndProject
Expand All @@ -12,6 +12,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Mockaco.Tests", "test\Mockaco.Tests\Mockaco.Tests.csproj", "{EE57B1B4-29D2-4AE3-8F23-5E622302C30F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mockaco.AspNetCore", "src\Mockaco.AspNetCore\Mockaco.AspNetCore.csproj", "{7766C592-9887-4162-8B9C-51003ED30335}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -29,6 +31,12 @@ Global
{EE57B1B4-29D2-4AE3-8F23-5E622302C30F}.Nuget|Any CPU.ActiveCfg = Release|Any CPU
{EE57B1B4-29D2-4AE3-8F23-5E622302C30F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EE57B1B4-29D2-4AE3-8F23-5E622302C30F}.Release|Any CPU.Build.0 = Release|Any CPU
{7766C592-9887-4162-8B9C-51003ED30335}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7766C592-9887-4162-8B9C-51003ED30335}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7766C592-9887-4162-8B9C-51003ED30335}.Nuget|Any CPU.ActiveCfg = Debug|Any CPU
{7766C592-9887-4162-8B9C-51003ED30335}.Nuget|Any CPU.Build.0 = Debug|Any CPU
{7766C592-9887-4162-8B9C-51003ED30335}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7766C592-9887-4162-8B9C-51003ED30335}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
16 changes: 16 additions & 0 deletions checkBuild.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
dotnet restore --verbosity normal
dotnet build --configuration Release --verbosity normal .\src\Mockaco\Mockaco.csproj
dotnet test --configuration Release --verbosity normal .\test\Mockaco.Tests\Mockaco.Tests.csproj
dotnet pack --configuration Nuget --output ./nupkg
docker build -f ./src/Mockaco/Docker/Dockerfile -t mockaco:local .

$containerName = [guid]::NewGuid().ToString()
try {
docker run --name $containerName -d -p 5000:5000 -v ${PSScriptRoot}/src/Mockaco/Mocks:/app/Mocks mockaco:local
Start-Sleep -Seconds 5
docker run --rm -v ${PSScriptRoot}/test/_postman:/etc/newman -t postman/newman:alpine run Mockaco.postman_collection.json
}
finally {
docker container stop $containerName
docker container rm $containerName
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace Mockaco
{
public static class HttpContentTypes
internal static class HttpContentTypes
{
public const string ApplicationOctetStream = "application/octet-stream";
public const string ApplicationJson = "application/json";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace Mockaco
{
public static class HttpHeaders
internal static class HttpHeaders
{
public const string ContentType = "Content-Type";
public const string AcceptLanguage = "Accept-Language";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace Mockaco
{
public class RouteMatcher
internal class RouteMatcher
{
public RouteValueDictionary Match(string routeTemplate, string requestPath)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Mockaco;
using Mockaco.Verifyer;

namespace Microsoft.AspNetCore.Builder
{
public static class MockacoApplicationBuilder
{
public static IApplicationBuilder UseMockaco(this IApplicationBuilder app, Action<IApplicationBuilder> configure)
{
var options = app.ApplicationServices.GetRequiredService<IOptions<MockacoOptions>>().Value;
app.UseEndpoints(endpoints => endpoints.Map($"/{options.VerificationEndpointPrefix}/{options.VerificationEndpointName}", VerifyerExtensions.Verify));

app.UseMiddleware<ErrorHandlingMiddleware>();
configure(app);
app
.UseMiddleware<ResponseDelayMiddleware>()
.UseMiddleware<RequestMatchingMiddleware>()
.UseMiddleware<ResponseMockingMiddleware>()
.UseMiddleware<CallbackMiddleware>();

return app;
}

public static IApplicationBuilder UseMockaco(this IApplicationBuilder app) =>
app.UseMockaco(_ => { });
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Mockaco;
using Mockaco.Settings;

namespace Microsoft.Extensions.DependencyInjection
{
public static class MockacoServiceCollection
{
public static IServiceCollection AddMockaco(this IServiceCollection services) =>
services.AddMockaco(_ => { });

public static IServiceCollection AddMockaco(this IServiceCollection services, Action<MockacoOptions> config) =>
services
.AddOptions<MockacoOptions>().Configure(config).Services
.AddOptions<TemplateFileProviderOptions>()
.Configure<IOptions<MockacoOptions>>((options, parent) => options = parent.Value.TemplateFileProvider)
.Services
.AddCommonServices();

public static IServiceCollection AddMockaco(this IServiceCollection services, IConfiguration config) =>
services
.AddConfiguration(config)
.AddCommonServices();

private static IServiceCollection AddConfiguration(this IServiceCollection services, IConfiguration config) =>
services
.AddOptions()
.Configure<MockacoOptions>(config)
.Configure<TemplateFileProviderOptions>(config.GetSection("TemplateFileProvider"));

private static IServiceCollection AddCommonServices(this IServiceCollection services) =>
services
.AddMemoryCache()
.AddHttpClient()
.AddInternalServices()
.AddHostedService<MockProviderWarmUp>();

private static IServiceCollection AddInternalServices(this IServiceCollection services) =>
services
.AddSingleton<VerificationRouteValueTransformer>()
.AddScoped<IMockacoContext, MockacoContext>()
.AddScoped<IScriptContext, ScriptContext>()
.AddTransient<IGlobalVariableStorage, ScriptContextGlobalVariableStorage>()

.AddSingleton<IScriptRunnerFactory, ScriptRunnerFactory>()

.AddSingleton<IFakerFactory, LocalizedFakerFactory>()
.AddSingleton<IMockProvider, MockProvider>()
.AddSingleton<ITemplateProvider, TemplateFileProvider>()

.AddScoped<IRequestMatcher, RequestMethodMatcher>()
.AddScoped<IRequestMatcher, RequestRouteMatcher>()
.AddScoped<IRequestMatcher, RequestConditionMatcher>()

.AddTransient<IRequestBodyFactory, RequestBodyFactory>()

.AddTransient<IRequestBodyStrategy, JsonRequestBodyStrategy>()
.AddTransient<IRequestBodyStrategy, XmlRequestBodyStrategy>()
.AddTransient<IRequestBodyStrategy, FormRequestBodyStrategy>()

.AddTransient<IResponseBodyFactory, ResponseBodyFactory>()

.AddTransient<IResponseBodyStrategy, BinaryResponseBodyStrategy>()
.AddTransient<IResponseBodyStrategy, JsonResponseBodyStrategy>()
.AddTransient<IResponseBodyStrategy, XmlResponseBodyStrategy>()
.AddTransient<IResponseBodyStrategy, DefaultResponseBodyStrategy>()

.AddTransient<ITemplateTransformer, TemplateTransformer>();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace System.Collections.Generic
{
public static class EnumerableExtensions
internal static class EnumerableExtensions
{
public static async Task<bool> AllAsync<TSource>(this IEnumerable<TSource> source, Func<TSource, Task<bool>> predicate)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ namespace Microsoft.AspNetCore.Http
/// <summary>
/// Set of extension methods for Microsoft.AspNetCore.Http.HttpRequest
/// </summary>
public static class HttpRequestExtensions
internal static class HttpRequestExtensions
{
private const string UnknownHostName = "UNKNOWN-HOST";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace System
{
public static class ObjectExtensions
internal static class ObjectExtensions
{
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace System.Collections.Generic
{
public static class StringDictionaryExtensions
internal static class StringDictionaryExtensions
{
public static StringDictionary ToStringDictionary<TSource>(
this IEnumerable<TSource> source,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace System
{
public static class StringExtensions
internal static class StringExtensions
{
public static string ToMD5Hash(this string input)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

namespace Mockaco
{
public interface IMockProvider
internal interface IMockProvider
{
List<Mock> GetMocks();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Mockaco
{
public interface IMockacoContext
internal interface IMockacoContext
{
IScriptContext ScriptContext { get; }

Expand Down
4 changes: 4 additions & 0 deletions src/Mockaco.AspNetCore/InternalsVisibleTo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Mockaco.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

namespace Mockaco
{
public class CallbackMiddleware
internal class CallbackMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<CallbackMiddleware> _logger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

namespace Mockaco
{
public class ErrorHandlingMiddleware
internal class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

namespace Mockaco
{
public class RequestMatchingMiddleware
internal class RequestMatchingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestMatchingMiddleware> _logger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace Mockaco
{
public class ResponseDelayMiddleware
internal class ResponseDelayMiddleware
{
private readonly RequestDelegate _next;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace Mockaco
{
public class ResponseMockingMiddleware
internal class ResponseMockingMiddleware
{
private readonly RequestDelegate _next;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

namespace Mockaco
{
public class MockProvider : IMockProvider
internal class MockProvider : IMockProvider
{
private List<Mock> _cache;
private readonly List<(string TemplateName, string ErrorMessage)> _errors = new List<(string TemplateName, string Error)>();
Expand Down
54 changes: 54 additions & 0 deletions src/Mockaco.AspNetCore/Mockaco.AspNetCore.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>latest</LangVersion>
<AssemblyName>Mockaco.AspNetCore</AssemblyName>
<RootNamespace>Mockaco</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Configurations>Debug;Release;Nuget</Configurations>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>

<PropertyGroup>
<IsPackable>true</IsPackable>
<PackageOutputPath>./nupkg</PackageOutputPath>
<PackageRequireLicenseAcceptance>false</PackageRequireLicenseAcceptance>
<Authors>natenho</Authors>
<Description>ASP.NET Core pipeline to mock HTTP requests/responses, useful to stub services and simulate dynamic API responses, leveraging ASP.NET Core features, built-in fake data generation and pure C# scripting</Description>
<PackageProjectUrl>https://github.com/natenho/Mockaco</PackageProjectUrl>
<RepositoryUrl>https://github.com/natenho/Mockaco</RepositoryUrl>
<PackageTags>mock http aspnetcore</PackageTags>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<PackageIcon>mockaco-icon.png</PackageIcon>
<Product>Mockaco</Product>
</PropertyGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Bogus" Version="33.0.2" />
<PackageReference Include="GitVersion.MsBuild" Version="5.6.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="MAB.DotIgnore" Version="3.0.2" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="3.9.0" />
<PackageReference Include="Microsoft.CodeAnalysis.PublicApiAnalyzers" Version="3.3.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Polly" Version="7.2.2" />
</ItemGroup>

<ItemGroup>
<None Include="Resources\mockaco-icon.png">
<Pack>True</Pack>
<PackagePath>/</PackagePath>
</None>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Mockaco
{
public class MockacoContext : IMockacoContext
internal class MockacoContext : IMockacoContext
{
public IScriptContext ScriptContext { get; set; }

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Collections.Generic;
using System.Net;
using System.Net;

namespace Mockaco
{
Expand All @@ -17,13 +16,23 @@ public class MockacoOptions

public int MatchedRoutesCacheDuration { get; set; }

public string VerificationEndpointPrefix { get; set; }

public string VerificationEndpointName { get; set; }

public TemplateFileProviderOptions TemplateFileProvider { get; set; }

public MockacoOptions()
{
DefaultHttpStatusCode = HttpStatusCode.OK;
ErrorHttpStatusCode = HttpStatusCode.NotImplemented;
DefaultHttpContentType = HttpContentTypes.ApplicationJson;
References = new List<string>();
Imports = new List<string>();
MatchedRoutesCacheDuration = 60;
VerificationEndpointPrefix = "_mockaco";
VerificationEndpointName = "verification";
TemplateFileProvider = new();
}
}
}
Loading