From 47c0e5b5b320aaab7b925db01c4137ec780f8ad5 Mon Sep 17 00:00:00 2001 From: Renato Lima Date: Sun, 11 Jun 2023 01:31:11 -0300 Subject: [PATCH 1/8] Try to create mock root folder if not exists --- .../Templating/Providers/TemplateFileProvider.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Mockaco.AspNetCore/Templating/Providers/TemplateFileProvider.cs b/src/Mockaco.AspNetCore/Templating/Providers/TemplateFileProvider.cs index 3881a00..e4172f9 100644 --- a/src/Mockaco.AspNetCore/Templating/Providers/TemplateFileProvider.cs +++ b/src/Mockaco.AspNetCore/Templating/Providers/TemplateFileProvider.cs @@ -54,7 +54,12 @@ private void SetMockRootPath(string path) var fullPath = Path.IsPathRooted(path) ? path : Path.Combine(Directory.GetCurrentDirectory(), path); - + + if (!Directory.Exists(fullPath)) + { + Directory.CreateDirectory(fullPath); + } + var fileProvider = new PhysicalFileProvider(fullPath, ExclusionFilters.Hidden | ExclusionFilters.System); _fileProvider?.Dispose(); From 25f0c5b66cb711356f3afe86b12f04618c3e47c7 Mon Sep 17 00:00:00 2001 From: Renato Lima Date: Sun, 11 Jun 2023 13:22:17 -0300 Subject: [PATCH 2/8] Add health and ready endpoints Closes #105 --- .../MockacoApplicationBuilder.cs | 20 ++++++++++++++- .../MockacoServiceCollection.cs | 13 +++++++++- .../HealthChecks/StartupHealthCheck.cs | 25 +++++++++++++++++++ src/Mockaco.AspNetCore/MockProvider.cs | 9 ++++++- .../Mockaco.AspNetCore.csproj | 20 +++++++++------ .../Options/MockacoOptions.cs | 5 +++- .../PublicAPI.Unshipped.txt | 7 ++++++ 7 files changed, 88 insertions(+), 11 deletions(-) create mode 100644 src/Mockaco.AspNetCore/HealthChecks/StartupHealthCheck.cs diff --git a/src/Mockaco.AspNetCore/DependencyInjection/MockacoApplicationBuilder.cs b/src/Mockaco.AspNetCore/DependencyInjection/MockacoApplicationBuilder.cs index bcca80f..ce0d3bc 100644 --- a/src/Mockaco.AspNetCore/DependencyInjection/MockacoApplicationBuilder.cs +++ b/src/Mockaco.AspNetCore/DependencyInjection/MockacoApplicationBuilder.cs @@ -2,6 +2,9 @@ using Microsoft.Extensions.Options; using Mockaco; using Mockaco.Verifyer; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics.HealthChecks; namespace Microsoft.AspNetCore.Builder { @@ -10,8 +13,23 @@ public static class MockacoApplicationBuilder public static IApplicationBuilder UseMockaco(this IApplicationBuilder app, Action configure) { app.UseRouting(); + var options = app.ApplicationServices.GetRequiredService>().Value; - app.UseEndpoints(endpoints => endpoints.Map($"/{options.VerificationEndpointPrefix}/{options.VerificationEndpointName}", VerifyerExtensions.Verify)); + + app.UseEndpoints(endpoints => + { + endpoints.Map($"/{options.VerificationEndpointPrefix ?? options.MockacoEndpoint}/{options.VerificationEndpointName}", VerifyerExtensions.Verify); + + endpoints.MapHealthChecks($"/{options.MockacoEndpoint}/ready", new HealthCheckOptions + { + Predicate = healthCheck => healthCheck.Tags.Contains("ready") + }); + + endpoints.MapHealthChecks($"/{options.MockacoEndpoint}/health", new HealthCheckOptions + { + Predicate = _ => false + }); + }); app.UseMiddleware(); configure(app); diff --git a/src/Mockaco.AspNetCore/DependencyInjection/MockacoServiceCollection.cs b/src/Mockaco.AspNetCore/DependencyInjection/MockacoServiceCollection.cs index aa70416..9094cb1 100644 --- a/src/Mockaco.AspNetCore/DependencyInjection/MockacoServiceCollection.cs +++ b/src/Mockaco.AspNetCore/DependencyInjection/MockacoServiceCollection.cs @@ -1,6 +1,8 @@ using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; using Mockaco; +using Mockaco.HealthChecks; using Mockaco.Settings; namespace Microsoft.Extensions.DependencyInjection @@ -30,13 +32,22 @@ private static IServiceCollection AddConfiguration(this IServiceCollection servi .Configure(config) .Configure(config.GetSection("TemplateFileProvider")); - private static IServiceCollection AddCommonServices(this IServiceCollection services) => + private static IServiceCollection AddCommonServices(this IServiceCollection services) + { services .AddMemoryCache() .AddHttpClient() .AddInternalServices() .AddHostedService(); + services + .AddSingleton() + .AddHealthChecks() + .AddCheck("Startup", tags: new[] { "ready" }); + + return services; + } + private static IServiceCollection AddInternalServices(this IServiceCollection services) => services .AddSingleton() diff --git a/src/Mockaco.AspNetCore/HealthChecks/StartupHealthCheck.cs b/src/Mockaco.AspNetCore/HealthChecks/StartupHealthCheck.cs new file mode 100644 index 0000000..164b7d3 --- /dev/null +++ b/src/Mockaco.AspNetCore/HealthChecks/StartupHealthCheck.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.Diagnostics.HealthChecks; + +namespace Mockaco.HealthChecks +{ + public class StartupHealthCheck : IHealthCheck + { + private volatile bool _isReady; + + public bool StartupCompleted + { + get => _isReady; + set => _isReady = value; + } + + public Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) + { + if (StartupCompleted) + { + return Task.FromResult(HealthCheckResult.Healthy("The startup has completed.")); + } + + return Task.FromResult(HealthCheckResult.Unhealthy("That startup is still running.")); + } + } +} diff --git a/src/Mockaco.AspNetCore/MockProvider.cs b/src/Mockaco.AspNetCore/MockProvider.cs index 9cac775..a4562e4 100644 --- a/src/Mockaco.AspNetCore/MockProvider.cs +++ b/src/Mockaco.AspNetCore/MockProvider.cs @@ -1,4 +1,6 @@ -using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Diagnostics.HealthChecks; +using Microsoft.Extensions.Logging; +using Mockaco.HealthChecks; using Mono.TextTemplating; using Newtonsoft.Json; using System; @@ -18,6 +20,7 @@ internal class MockProvider : IMockProvider private readonly ITemplateProvider _templateProvider; private readonly ITemplateTransformer _templateTransformer; private readonly IGlobalVariableStorage _globalVariableStorage; + private readonly StartupHealthCheck _healthCheck; private readonly ILogger _logger; public MockProvider @@ -26,6 +29,7 @@ public MockProvider ITemplateProvider templateProvider, ITemplateTransformer templateTransformer, IGlobalVariableStorage globalVariableStorage, + StartupHealthCheck healthCheck, ILogger logger) { _cache = new List(); @@ -36,6 +40,7 @@ public MockProvider _templateTransformer = templateTransformer; _globalVariableStorage = globalVariableStorage; + _healthCheck = healthCheck; _logger = logger; } @@ -114,6 +119,8 @@ public async Task WarmUp() _cache = mocks.OrderByDescending(r => r.HasCondition).ToList(); + _healthCheck.StartupCompleted = true; + _logger.LogTrace("{0} finished in {1} ms", nameof(WarmUp), stopwatch.ElapsedMilliseconds); } diff --git a/src/Mockaco.AspNetCore/Mockaco.AspNetCore.csproj b/src/Mockaco.AspNetCore/Mockaco.AspNetCore.csproj index 999733f..d48f1a4 100644 --- a/src/Mockaco.AspNetCore/Mockaco.AspNetCore.csproj +++ b/src/Mockaco.AspNetCore/Mockaco.AspNetCore.csproj @@ -44,23 +44,29 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - + + + + + <_Parameter1>Mockaco.Tests + + + True diff --git a/src/Mockaco.AspNetCore/Options/MockacoOptions.cs b/src/Mockaco.AspNetCore/Options/MockacoOptions.cs index d61e01a..a431aa6 100644 --- a/src/Mockaco.AspNetCore/Options/MockacoOptions.cs +++ b/src/Mockaco.AspNetCore/Options/MockacoOptions.cs @@ -16,6 +16,9 @@ public class MockacoOptions public int MatchedRoutesCacheDuration { get; set; } + public string MockacoEndpoint { get; set; } + + // Deprecated (use MockacoEndpoint instead) public string VerificationEndpointPrefix { get; set; } public string VerificationEndpointName { get; set; } @@ -30,7 +33,7 @@ public MockacoOptions() References = new List(); Imports = new List(); MatchedRoutesCacheDuration = 60; - VerificationEndpointPrefix = "_mockaco"; + MockacoEndpoint = "_mockaco"; VerificationEndpointName = "verification"; TemplateFileProvider = new(); } diff --git a/src/Mockaco.AspNetCore/PublicAPI.Unshipped.txt b/src/Mockaco.AspNetCore/PublicAPI.Unshipped.txt index 539725c..1f096d4 100644 --- a/src/Mockaco.AspNetCore/PublicAPI.Unshipped.txt +++ b/src/Mockaco.AspNetCore/PublicAPI.Unshipped.txt @@ -1,6 +1,11 @@ Bogus.PhoneNumberExtensions Microsoft.AspNetCore.Builder.MockacoApplicationBuilder Microsoft.Extensions.DependencyInjection.MockacoServiceCollection +Mockaco.HealthChecks.StartupHealthCheck +Mockaco.HealthChecks.StartupHealthCheck.CheckHealthAsync(Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckContext context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task +Mockaco.HealthChecks.StartupHealthCheck.StartupCompleted.get -> bool +Mockaco.HealthChecks.StartupHealthCheck.StartupCompleted.set -> void +Mockaco.HealthChecks.StartupHealthCheck.StartupHealthCheck() -> void Mockaco.IFakerFactory Mockaco.IFakerFactory.GetDefaultFaker() -> Bogus.Faker Mockaco.IFakerFactory.GetFaker(System.Collections.Generic.IEnumerable acceptLanguages) -> Bogus.Faker @@ -47,6 +52,8 @@ Mockaco.MockacoOptions.Imports.get -> System.Collections.Generic.List Mockaco.MockacoOptions.Imports.set -> void Mockaco.MockacoOptions.MatchedRoutesCacheDuration.get -> int Mockaco.MockacoOptions.MatchedRoutesCacheDuration.set -> void +Mockaco.MockacoOptions.MockacoEndpoint.get -> string +Mockaco.MockacoOptions.MockacoEndpoint.set -> void Mockaco.MockacoOptions.MockacoOptions() -> void Mockaco.MockacoOptions.References.get -> System.Collections.Generic.List Mockaco.MockacoOptions.References.set -> void From ab5725103df6761f045ce0f92377d8afac516098 Mon Sep 17 00:00:00 2001 From: Renato Lima Date: Sun, 11 Jun 2023 13:22:59 -0300 Subject: [PATCH 3/8] Upgrade packages --- src/Mockaco/Mockaco.csproj | 14 ++-- test/Mockaco.Tests/Mockaco.Tests.csproj | 79 ++++++++++--------- .../Request/JsonRequestBodyStrategyTest.cs | 2 +- test/Mockaco.Tests/Usings.cs | 1 + 4 files changed, 51 insertions(+), 45 deletions(-) create mode 100644 test/Mockaco.Tests/Usings.cs diff --git a/src/Mockaco/Mockaco.csproj b/src/Mockaco/Mockaco.csproj index 2da941b..3fd3e04 100644 --- a/src/Mockaco/Mockaco.csproj +++ b/src/Mockaco/Mockaco.csproj @@ -44,16 +44,16 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - + + + + + + diff --git a/test/Mockaco.Tests/Mockaco.Tests.csproj b/test/Mockaco.Tests/Mockaco.Tests.csproj index 4772d50..422ea78 100644 --- a/test/Mockaco.Tests/Mockaco.Tests.csproj +++ b/test/Mockaco.Tests/Mockaco.Tests.csproj @@ -1,45 +1,50 @@  - - net6.0 - false - + + net6.0 + Mockaco.Tests + enable + enable - - - Always - - + false + true + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - + + + - - - + + + Always + + - - - PreserveNewest - Always - - - Always - PreserveNewest - - + + + PreserveNewest + Always + + + Always + PreserveNewest + + diff --git a/test/Mockaco.Tests/Templating/Request/JsonRequestBodyStrategyTest.cs b/test/Mockaco.Tests/Templating/Request/JsonRequestBodyStrategyTest.cs index 7b41a10..bd95686 100644 --- a/test/Mockaco.Tests/Templating/Request/JsonRequestBodyStrategyTest.cs +++ b/test/Mockaco.Tests/Templating/Request/JsonRequestBodyStrategyTest.cs @@ -52,7 +52,7 @@ public void Throws_Exception_When_Request_Has_Invalid_Json(string givenBody) bodyStrategy.Invoking(async _ => await _.ReadBodyAsJson(httpRequest.Object)) .Should() - .Throw(); + .ThrowAsync(); } [Theory] diff --git a/test/Mockaco.Tests/Usings.cs b/test/Mockaco.Tests/Usings.cs new file mode 100644 index 0000000..8c927eb --- /dev/null +++ b/test/Mockaco.Tests/Usings.cs @@ -0,0 +1 @@ +global using Xunit; \ No newline at end of file From ef465a1984a76d613b802d80bdd5be4c1737408b Mon Sep 17 00:00:00 2001 From: Renato Lima Date: Sun, 11 Jun 2023 14:00:10 -0300 Subject: [PATCH 4/8] Add docs for configuration --- website/docs/configuration/_category_.json | 4 ++ website/docs/configuration/index.md | 59 ++++++++++++++++++++++ website/docs/verification/index.md | 2 +- 3 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 website/docs/configuration/_category_.json create mode 100644 website/docs/configuration/index.md diff --git a/website/docs/configuration/_category_.json b/website/docs/configuration/_category_.json new file mode 100644 index 0000000..feecc5f --- /dev/null +++ b/website/docs/configuration/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Configuration", + "position": 7 +} diff --git a/website/docs/configuration/index.md b/website/docs/configuration/index.md new file mode 100644 index 0000000..c991479 --- /dev/null +++ b/website/docs/configuration/index.md @@ -0,0 +1,59 @@ +# Configuration + +The configuration can be made in the `appsettings.json` file inside `Settings` folder. + +## `DefaultHttpStatusCode` + +Set the default HTTP status code returned when the mock does not specify one. + +Default: `OK` (200) + +## `ErrorHttpStatusCode` + +Set the default HTTP status code in case there is no matching mock available. + +Default: `NotImplemented` (501) + +## `DefaultHttpContentType` + +Set the default HTTP `Content-Type` header response when the mock does not specify one. + +Default: `application/json` + +## `References` + +A list of references to other .NET assemblies to extend scripting engine. + +Default: `[]` + +## `Imports` + +A list of namespaces to be imported and made available in scripting engine. + +Default: `[]` + +## `MatchedRoutesCacheDuration` + +Set the cache duration in minutes to be used by the verification endpoint. + +## `MockacoEndpoint` + +The exclusive endpoint to access internal features. + +Default: `_mockaco` + +## `VerificationEndpointName` + +The name of the verification endpoint. + +Default: `verification` + +## `TemplateFileProvider` + +Configure the mock template file provider. + +### `Path` + +Define the mock template files path. + +Default: `Mocks` \ No newline at end of file diff --git a/website/docs/verification/index.md b/website/docs/verification/index.md index 97b19f7..baac891 100644 --- a/website/docs/verification/index.md +++ b/website/docs/verification/index.md @@ -53,7 +53,7 @@ You will be able to access the verification endpoint on ```http://localhost:5000 ## Configure the duration of cache storing last request for verification -Each request with the exact time of being ivoked, body and path is being stored in the internal .Net cache for 60 minutes. You can configure this time by changing +Each request with the exact time of being invoked, body and path is being stored in the internal .Net cache for 60 minutes. You can configure this time by changing ``` "Mockaco": { From 1b729660ab74e60e3f98a32891ea92a61e28ce0d Mon Sep 17 00:00:00 2001 From: Renato Lima Date: Sun, 11 Jun 2023 14:01:07 -0300 Subject: [PATCH 5/8] Adjust docs --- website/docs/configuration/index.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/website/docs/configuration/index.md b/website/docs/configuration/index.md index c991479..df1bc6e 100644 --- a/website/docs/configuration/index.md +++ b/website/docs/configuration/index.md @@ -36,6 +36,8 @@ Default: `[]` Set the cache duration in minutes to be used by the verification endpoint. +Default: `60` + ## `MockacoEndpoint` The exclusive endpoint to access internal features. From e6d01b3d41a5df8f9fac3c62568907a90d591abf Mon Sep 17 00:00:00 2001 From: Renato Lima Date: Sun, 11 Jun 2023 14:16:55 -0300 Subject: [PATCH 6/8] Fix obsolete Serilog usage --- src/Mockaco/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Mockaco/Program.cs b/src/Mockaco/Program.cs index 05816a3..8447473 100644 --- a/src/Mockaco/Program.cs +++ b/src/Mockaco/Program.cs @@ -48,9 +48,9 @@ public static IHostBuilder CreateHostBuilder(string[] args) => configuration.AddCommandLine(args, switchMappings); }) - .UseSerilog((context, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(context.Configuration)) .UseStartup(); - }); + }) + .UseSerilog((context, loggerConfiguration) => loggerConfiguration.ReadFrom.Configuration(context.Configuration)); private static CommandLineBuilder CreateCommandLineBuilder(string[] args, IHost host) { From f3386964f9e82c7c98b126f1a40bad4c6a1c2067 Mon Sep 17 00:00:00 2001 From: Renato Lima Date: Sun, 11 Jun 2023 15:28:41 -0300 Subject: [PATCH 7/8] Add health check docs --- .dockerignore | 3 +- website/docs/guides/_category_.json | 2 +- website/docs/health-checks/_category_.json | 4 + website/docs/health-checks/index.md | 90 ++++++++++++++++++++++ 4 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 website/docs/health-checks/_category_.json create mode 100644 website/docs/health-checks/index.md diff --git a/.dockerignore b/.dockerignore index abb7940..2fc18b0 100644 --- a/.dockerignore +++ b/.dockerignore @@ -265,8 +265,9 @@ __pycache__/ **/.dockerignore **/*.md .github/ -doc/ +nupkg/ test/ +website/ **/*.log src/Mockaco/Mocks*/**/*.* !src/Mockaco/Mocks/hello.json \ No newline at end of file diff --git a/website/docs/guides/_category_.json b/website/docs/guides/_category_.json index 0a91d39..3f3143c 100644 --- a/website/docs/guides/_category_.json +++ b/website/docs/guides/_category_.json @@ -1,6 +1,6 @@ { "label": "Guides", - "position": 10, + "position": 100, "link": { "type": "generated-index", "description": "5 minutes to learn the most important Docusaurus concepts." diff --git a/website/docs/health-checks/_category_.json b/website/docs/health-checks/_category_.json new file mode 100644 index 0000000..d3a0905 --- /dev/null +++ b/website/docs/health-checks/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Health Checks", + "position": 8 +} diff --git a/website/docs/health-checks/index.md b/website/docs/health-checks/index.md new file mode 100644 index 0000000..5e247e2 --- /dev/null +++ b/website/docs/health-checks/index.md @@ -0,0 +1,90 @@ +# Health Checks + +Health checks are often useful when Mockaco container is being used. + +## `/_mockaco/health` + +To determine if Mockaco is running and listening, you can check its health status by accessing http://localhost:5000/_mockaco/health. A successful request will receive an HTTP 200 OK response. + +``` +$ curl -i http://localhost:5000/_mockaco/health +HTTP/1.1 200 OK +Content-Type: text/plain +Date: Sun, 11 Jun 2023 17:46:30 GMT +Server: Kestrel +Cache-Control: no-store, no-cache +Expires: Thu, 01 Jan 1970 00:00:00 GMT +Pragma: no-cache +Transfer-Encoding: chunked + +Healthy +``` + +## `/_mockaco/ready` + +During the startup process, Mockaco asynchronously loads and caches mocks. The duration of this process may vary depending on the number of mocks being loaded. However, it's important to note that while this loading is taking place, some requests may not be served as expected, resulting in an HTTP 501 response. + +To avoid this potential race condition, it is recommended to utilize the readiness endpoint. + +While the mocks are still loading, the service will respond with an HTTP 503 status code. Here's an example of the response you would receive: + +``` +$ curl -i http://localhost:5000/_mockaco/ready +HTTP/1.1 503 Service Unavailable +Content-Type: text/plain +Date: Sun, 11 Jun 2023 17:47:55 GMT +Server: Kestrel +Cache-Control: no-store, no-cache +Expires: Thu, 01 Jan 1970 00:00:00 GMT +Pragma: no-cache +Transfer-Encoding: chunked + +Unhealthy +``` + +Once the startup process is complete and Mockaco is ready to handle requests, the readiness endpoint will return an HTTP 200 OK status code. Here's an example: + +``` +$ curl -i http://localhost:5000/_mockaco/ready +HTTP/1.1 200 OK +Content-Type: text/plain +Date: Sun, 11 Jun 2023 17:50:59 GMT +Server: Kestrel +Cache-Control: no-store, no-cache +Expires: Thu, 01 Jan 1970 00:00:00 GMT +Pragma: no-cache +Transfer-Encoding: chunked + +Healthy +``` + +### Using readiness endpoint in Dockerfile + +By default, Mockaco containers does not expose health checks. However, you can create a derived Docker image and utilize the `HEALTHCHECK` instruction to ensure the container's health status is determined only after all the mocks have been loaded. Here's an example Dockerfile: + +```Dockerfile +FROM natenho/mockaco +COPY Mocks /app/Mocks +HEALTHCHECK --interval=5s --timeout=3s \ + CMD curl --fail http://localhost:5000/_mockaco/ready || exit 1 +``` + +In this Dockerfile, the `Mocks` folder is copied into the `/app/Mocks` directory within the container. You can replace Mocks with the actual path of your local Mocks folder. + +The `HEALTHCHECK` instruction sets up a health check for the container. It specifies the interval and timeout for checking the health, and it runs the curl command to verify the readiness endpoint `http://localhost:5000/_mockaco/ready`. If the curl command fails (returns a non-zero exit status), the container will be considered unhealthy and exit with status code 1. + +To build the derived Docker image, use the following command: + +```shell +docker build -t mockaco-image . +``` + +Replace mockaco-image with your desired image name. + +Once the image is built, you can run a container based on it, mapping the container's port 5000 to the host's port of your choice (e.g., 8080): + +```shell +docker run -d -p 8080:5000 --name mockaco-container mockaco-image +``` + +Now the container will be running with the Mocks folder mapped to `/app/Mocks` inside it, and the health check will be performed periodically using the specified curl command. \ No newline at end of file From ce871d8c7b96e351951d879a4946a303fa20862e Mon Sep 17 00:00:00 2001 From: Renato Lima Date: Sun, 11 Jun 2023 16:00:48 -0300 Subject: [PATCH 8/8] Improve configuration docs --- src/Mockaco/Settings/appsettings.json | 6 +-- website/docs/configuration/index.md | 66 ++++++++++++++++++++++----- 2 files changed, 57 insertions(+), 15 deletions(-) diff --git a/src/Mockaco/Settings/appsettings.json b/src/Mockaco/Settings/appsettings.json index c522b29..7169ce6 100644 --- a/src/Mockaco/Settings/appsettings.json +++ b/src/Mockaco/Settings/appsettings.json @@ -5,9 +5,9 @@ "DefaultHttpContentType": "application/json", "References": [], "Imports": [], - "MatchedRoutesCacheDuration": 60, - "VerificationEndpointName": "verification", - "VerificationEndpointPrefix": "_mockaco" + "MatchedRoutesCacheDuration": 60, + "MockacoEndpoint": "_mockaco", + "VerificationEndpointName": "verification" }, "AllowedHosts": "*", "Serilog": { diff --git a/website/docs/configuration/index.md b/website/docs/configuration/index.md index df1bc6e..045ece5 100644 --- a/website/docs/configuration/index.md +++ b/website/docs/configuration/index.md @@ -1,61 +1,103 @@ # Configuration -The configuration can be made in the `appsettings.json` file inside `Settings` folder. +The configuration for Mockaco can be easily customized using the appsettings*.json files located within the Settings folder. These files allow you to configure various options provided by ASP.NET Core. -## `DefaultHttpStatusCode` +Here are the different appsettings*.json files and their purposes: + +- *appsettings.Production.json*: Use this file to customize Mockaco when running it as an executable or dotnet tool. +- *appsettings.Docker.json*: This file is specifically used to customize Mockaco when running it within a Docker container. +- *appsettings.Development.json*: When running Mockaco in debug mode, such as inside Visual Studio, you can use this file to customize its behavior. This environment is typically set through the launchSettings.json file. + +These appsettings*.json files provide a convenient way to adjust Mockaco's settings based on the specific environment in which it is running. + +To customize Mockaco, locate the appropriate appsettings*.json file based on your deployment scenario and modify the configuration options according to your requirements. + +For instance you could override the default URLs Mockaco will listen to, just by changing the configuration like this: + +```json +{ + "Urls": "http://+:8080;https://+:8443" +} +``` + +Mockaco specific options are listed in the next topics. + +## Mockaco + +```json +{ + "Mockaco": { + "DefaultHttpStatusCode": "OK", + "ErrorHttpStatusCode": "NotImplemented", + "DefaultHttpContentType": "application/json", + "References": [], + "Imports": [], + "MatchedRoutesCacheDuration": 60, + "MockacoEndpoint": "_mockaco", + "VerificationEndpointName": "verification" + } +} +``` + +### `DefaultHttpStatusCode` Set the default HTTP status code returned when the mock does not specify one. Default: `OK` (200) -## `ErrorHttpStatusCode` +### `ErrorHttpStatusCode` Set the default HTTP status code in case there is no matching mock available. Default: `NotImplemented` (501) -## `DefaultHttpContentType` +### `DefaultHttpContentType` Set the default HTTP `Content-Type` header response when the mock does not specify one. Default: `application/json` -## `References` +### `References` A list of references to other .NET assemblies to extend scripting engine. Default: `[]` -## `Imports` +### `Imports` A list of namespaces to be imported and made available in scripting engine. Default: `[]` -## `MatchedRoutesCacheDuration` +### `MatchedRoutesCacheDuration` Set the cache duration in minutes to be used by the verification endpoint. Default: `60` -## `MockacoEndpoint` +### `MockacoEndpoint` The exclusive endpoint to access internal features. Default: `_mockaco` -## `VerificationEndpointName` +### `VerificationEndpointName` The name of the verification endpoint. Default: `verification` -## `TemplateFileProvider` +### `TemplateFileProvider` Configure the mock template file provider. -### `Path` +#### `Path` Define the mock template files path. -Default: `Mocks` \ No newline at end of file +Default: `Mocks` + +## `Serilog` + +Configure [Serilog logger](https://github.com/serilog/serilog-settings-configuration) +