Skip to content

Commit

Permalink
Updated SwaggerSnapshotTests to use Swaggger.json from the build of W…
Browse files Browse the repository at this point in the history
…ebApi
  • Loading branch information
Fargekritt committed Jan 23, 2025
1 parent 948579b commit fd86499
Show file tree
Hide file tree
Showing 8 changed files with 5,756 additions and 12,757 deletions.
6,985 changes: 0 additions & 6,985 deletions docs/schema/V1/swagger.json

This file was deleted.

11,430 changes: 5,715 additions & 5,715 deletions docs/schema/V1/swagger.verified.json

Large diffs are not rendered by default.

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

<Target Name="NSwag" AfterTargets="Build" Condition="$(Configuration)=='Release'">
<Exec WorkingDirectory="$(ProjectDir)" EnvironmentVariables="ASPNETCORE_ENVIRONMENT=Development" Command="$(NSwagExe_net90) aspnetcore2openapi /nobuild:true /project:$(MSBuildProjectFullPath) /configuration:$(Configuration) /output:$(MSBuildProjectDirectory)/../../docs/schema/v1/swagger.json"/>
<Exec WorkingDirectory="$(ProjectDir)" EnvironmentVariables="ASPNETCORE_ENVIRONMENT=Development" Command="$(NSwagExe_net90) aspnetcore2openapi /nobuild:true /project:$(MSBuildProjectFullPath) /configuration:$(Configuration) /output:$(TargetDir)/swagger.json"/>
</Target>


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public GetDialogActivityEndpointSummary()
{
Summary = "Gets a single dialog activity";
Description = """
Gets a single activity belonging to a dial og. For more information see the documentation (link TBD).
Gets a single activity belonging to a dialog. For more information see the documentation (link TBD).
""";
Responses[StatusCodes.Status200OK] = Constants.SwaggerSummary.ReturnedResult.FormatInvariant("activity");
Responses[StatusCodes.Status401Unauthorized] = Constants.SwaggerSummary.EndUserAuthenticationFailure;
Expand Down
64 changes: 22 additions & 42 deletions src/Digdir.Domain.Dialogporten.WebApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ static void BuildAndRun(string[] args)
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.WithEnvironmentName()
.Enrich.FromLogContext()
.Enrich.FromLogContext()
.WriteTo.OpenTelemetryOrConsole(context));

builder.Services
Expand Down Expand Up @@ -104,6 +104,26 @@ static void BuildAndRun(string[] args)
x.RemoveEmptyRequestSchema = true;
x.DocumentSettings = s =>
{
s.PostProcess = document =>
{
var dialogportenBaseUri = builder.Configuration
.GetSection(ApplicationSettings.ConfigurationSectionName)
.Get<ApplicationSettings>()!
.Dialogporten
.BaseUri
.ToString();

document.Servers.Clear();
document.Servers.Add(new OpenApiServer
{
Url = dialogportenBaseUri
});
document.Generator = null;
document.ReplaceProblemDetailsDescriptions();
document.MakeCollectionsNullable();
document.FixJwtBearerCasing();
document.RemoveSystemStringHeaderTitles();
};
s.Title = "Dialogporten";
s.DocumentName = "v1";
s.Version = "v1";
Expand Down Expand Up @@ -188,29 +208,7 @@ static void BuildAndRun(string[] args)
x.Errors.ResponseBuilder = ErrorResponseBuilderExtensions.ResponseBuilder;
})
.UseAddSwaggerCorsHeader()
.UseSwaggerGen(config =>
{
config.PostProcess = (document, _) =>
{
var dialogportenBaseUri = builder.Configuration
.GetSection(ApplicationSettings.ConfigurationSectionName)
.Get<ApplicationSettings>()!
.Dialogporten
.BaseUri
.ToString();

document.Servers.Clear();
document.Servers.Add(new OpenApiServer
{
Url = dialogportenBaseUri
});
document.Generator = null;
document.ReplaceProblemDetailsDescriptions();
document.MakeCollectionsNullable();
document.FixJwtBearerCasing();
document.RemoveSystemStringHeaderTitles();
};
}, uiConfig =>
.UseSwaggerGen(uiConfig: uiConfig =>
{
// Hide schemas view
uiConfig.DefaultModelsExpandDepth = -1;
Expand All @@ -219,24 +217,6 @@ static void BuildAndRun(string[] args)
uiConfig.DocumentPath = dialogPrefix + "/swagger/{documentName}/swagger.json";
});

/*await app.ExportSwaggerJsonAndExitAsync(
c =>
{
c.SwaggerDocumentName = "v1"; //must match doc name above
c.Language = GenerationLanguage.CSharp;
c.OutputPath = Path.Combine(app.Environment.WebRootPath, "ApiClients", "CSharp");
c.ClientNamespaceName = "MyCompanyName";
c.ClientClassName = "MyCsClient";
c.CreateZipArchive = true; //if you'd like a zip file as well
},
c =>
{
c.SwaggerDocumentName = "v1";
c.Language = GenerationLanguage.TypeScript;
c.OutputPath = Path.Combine(app.Environment.WebRootPath, "ApiClients", "Typescript");
c.ClientNamespaceName = "MyCompanyName";
c.ClientClassName = "MyTsClient";
});*/
app.Run();
}

Expand Down
2 changes: 1 addition & 1 deletion src/Digdir.Library.Dialogporten.WebApiClient/.refitter
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"openApiPath": "../../docs/schema/v1/swagger.json",
"openApiPath": "../Digdir.Domain.Dialogporten.WebApi/bin/Release/net9.0/swagger.json",
"namespace": "Digdir.Library.Dialogporten.WebApiClient.Features.V1",
"outputFolder": "Features/V1",
"operationNameGenerator": "SingleClientFromOperationId",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
<ItemGroup>
<None Include="README.md" Pack="true" PackagePath="/"/>
<None Include="../../LICENSE" Pack="true" PackagePath="/"/>
<None Include="../../docs/schema/v1/swagger.json"/>
<ProjectReference Include="..\Digdir.Domain.Dialogporten.WebApi\Digdir.Domain.Dialogporten.WebApi.csproj"
ReferenceOutputAssembly="false"
Condition="$(Configuration)=='Release'"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Text.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously

namespace Digdir.Domain.Dialogporten.WebApi.Integration.Tests.Features.V1;

Expand All @@ -17,37 +18,41 @@ public SwaggerSnapshotTests(WebApplicationFactory<Program> webApplicationFactory
[Fact]
public async Task FailIfSwaggerSnapshotDoesNotMatch()
{
#if RELEASE
// Arrange
// This test checks for changes against the published version of the swagger.verified.json file
// The file is located at /docs/schema/ on the solution root
// Commiting a change to this file will trigger a build and publish
// of the npm package located in the same folder
var rootPath = Utils.GetSolutionRootFolder();
var swaggerPath = Path.Combine(rootPath!, "docs/schema/V1");

var client = _webApplicationFactory
.WithWebHostBuilder(builder => builder.UseEnvironment("test"))
.CreateClient();

var newSwaggerPath = Path.Combine(rootPath!, "src/Digdir.Domain.Dialogporten.WebApi/bin/Release/net9.0/swagger.json");
// Act
var response = await client.GetAsync("/swagger/v1/swagger.json");
var newSwagger = await response.Content.ReadAsStringAsync();
var newSwagger = File.ReadAllText(newSwaggerPath);

// Amund: Stemmer dette lenger?
// The order of the properties in the swagger.json file is not cross-platform deterministic.
// Running client.GetAsync("/swagger/v1/swagger.json"); on Windows and Mac will produce
// different ordering of the results (although the content is the same). So we force an
// alphabetical ordering of the properties to make the test deterministic.
// Ref: https://github.com/altinn/dialogporten/issues/996
var orderedSwagger = SortJson(newSwagger);
// var orderedSwagger = SortJson(newSwagger);

// Assert
response.EnsureSuccessStatusCode();

await Verify(orderedSwagger, extension: "json")
await Verify(newSwagger, extension: "json")
.UseFileName("swagger")
.UseDirectory(swaggerPath);
#else
Assert.Fail("Swagger snapshot tests are not supported in DEBUG mode. Swagger is NOT generated in DEBUG mode, this is to keep build times low. therefore this test will always fail. Run in RELEASE mode to enable.");

#endif
}

private static readonly JsonSerializerOptions SerializerOptions = new() { WriteIndented = true };
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};

private static string SortJson(string jsonString)
{
Expand Down

0 comments on commit fd86499

Please sign in to comment.