Skip to content

OpenAPI: Client-generated IDs (continued) #1494

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

Merged
merged 2 commits into from
Mar 10, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
using FluentAssertions;
using FluentAssertions.Specialized;
using JsonApiDotNetCore.OpenApi.Client.NSwag;
using Newtonsoft.Json;
using OpenApiNSwagEndToEndTests.ClientIdGenerationModes.GeneratedCode;
using OpenApiTests;
using OpenApiTests.ClientIdGenerationModes;
using TestBuildingBlocks;
using Xunit;

namespace OpenApiNSwagEndToEndTests.ClientIdGenerationModes;

public sealed class ClientIdGenerationModesTests
: IClassFixture<IntegrationTestContext<OpenApiStartup<ClientIdGenerationModesDbContext>, ClientIdGenerationModesDbContext>>
{
private readonly IntegrationTestContext<OpenApiStartup<ClientIdGenerationModesDbContext>, ClientIdGenerationModesDbContext> _testContext;
private readonly ClientIdGenerationModesFakers _fakers = new();

public ClientIdGenerationModesTests(IntegrationTestContext<OpenApiStartup<ClientIdGenerationModesDbContext>, ClientIdGenerationModesDbContext> testContext)
{
_testContext = testContext;

testContext.UseController<PlayersController>();
testContext.UseController<GamesController>();
testContext.UseController<PlayerGroupsController>();
}

[Fact]
public async Task Cannot_create_resource_without_ID_when_supplying_ID_is_required()
{
// Arrange
Player player = _fakers.Player.Generate();

using HttpClient httpClient = _testContext.Factory.CreateClient();
ClientIdGenerationModesClient apiClient = new(httpClient);

// Act
Func<Task<PlayerPrimaryResponseDocument?>> action = () => ApiResponse.TranslateAsync(() => apiClient.PostPlayerAsync(null, new PlayerPostRequestDocument
{
Data = new PlayerDataInPostRequest
{
Id = null!,
Attributes = new PlayerAttributesInPostRequest
{
UserName = player.UserName
}
}
}));

// Assert
ExceptionAssertions<JsonSerializationException> assertion = await action.Should().ThrowExactlyAsync<JsonSerializationException>();
assertion.Which.Message.Should().Be("Cannot write a null value for property 'id'. Property requires a value. Path 'data'.");
}

[Fact]
public async Task Can_create_resource_with_ID_when_supplying_ID_is_required()
{
// Arrange
Player player = _fakers.Player.Generate();
player.Id = Guid.NewGuid();

using HttpClient httpClient = _testContext.Factory.CreateClient();
ClientIdGenerationModesClient apiClient = new(httpClient);

// Act
PlayerPrimaryResponseDocument? document = await ApiResponse.TranslateAsync(() => apiClient.PostPlayerAsync(null, new PlayerPostRequestDocument
{
Data = new PlayerDataInPostRequest
{
Id = player.StringId!,
Attributes = new PlayerAttributesInPostRequest
{
UserName = player.UserName
}
}
}));

// Assert
document.Should().BeNull();

await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Player playerInDatabase = await dbContext.Players.FirstWithIdAsync(player.Id);

playerInDatabase.UserName.Should().Be(player.UserName);
});
}

[Fact]
public async Task Can_create_resource_without_ID_when_supplying_ID_is_allowed()
{
// Arrange
Game game = _fakers.Game.Generate();

using HttpClient httpClient = _testContext.Factory.CreateClient();
ClientIdGenerationModesClient apiClient = new(httpClient);

// Act
GamePrimaryResponseDocument? document = await ApiResponse.TranslateAsync(() => apiClient.PostGameAsync(null, new GamePostRequestDocument
{
Data = new GameDataInPostRequest
{
Id = null!,
Attributes = new GameAttributesInPostRequest
{
Title = game.Title,
PurchasePrice = (double)game.PurchasePrice
}
}
}));

// Assert
document.ShouldNotBeNull();
document.Data.Id.Should().NotBeNullOrEmpty();

await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Game gameInDatabase = await dbContext.Games.FirstWithIdAsync(Guid.Parse(document.Data.Id));

gameInDatabase.Title.Should().Be(game.Title);
gameInDatabase.PurchasePrice.Should().Be(game.PurchasePrice);
});
}

[Fact]
public async Task Can_create_resource_with_ID_when_supplying_ID_is_allowed()
{
// Arrange
Game game = _fakers.Game.Generate();
game.Id = Guid.NewGuid();

using HttpClient httpClient = _testContext.Factory.CreateClient();
ClientIdGenerationModesClient apiClient = new(httpClient);

// Act
GamePrimaryResponseDocument? document = await ApiResponse.TranslateAsync(() => apiClient.PostGameAsync(null, new GamePostRequestDocument
{
Data = new GameDataInPostRequest
{
Id = game.StringId!,
Attributes = new GameAttributesInPostRequest
{
Title = game.Title,
PurchasePrice = (double)game.PurchasePrice
}
}
}));

// Assert
document.Should().BeNull();

await _testContext.RunOnDatabaseAsync(async dbContext =>
{
Game gameInDatabase = await dbContext.Games.FirstWithIdAsync(game.Id);

gameInDatabase.Title.Should().Be(game.Title);
gameInDatabase.PurchasePrice.Should().Be(game.PurchasePrice);
});
}

[Fact]
public async Task Can_create_resource_without_ID_when_supplying_ID_is_forbidden()
{
// Arrange
PlayerGroup playerGroup = _fakers.Group.Generate();

using HttpClient httpClient = _testContext.Factory.CreateClient();
ClientIdGenerationModesClient apiClient = new(httpClient);

// Act
PlayerGroupPrimaryResponseDocument? document = await ApiResponse.TranslateAsync(() => apiClient.PostPlayerGroupAsync(null,
new PlayerGroupPostRequestDocument
{
Data = new PlayerGroupDataInPostRequest
{
Attributes = new PlayerGroupAttributesInPostRequest
{
Name = playerGroup.Name
}
}
}));

// Assert
document.ShouldNotBeNull();
document.Data.Id.Should().NotBeNullOrEmpty();

await _testContext.RunOnDatabaseAsync(async dbContext =>
{
PlayerGroup playerGroupInDatabase = await dbContext.PlayerGroups.FirstWithIdAsync(long.Parse(document.Data.Id));

playerGroupInDatabase.Name.Should().Be(playerGroup.Name);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@
</ItemGroup>

<ItemGroup>
<OpenApiReference Include="..\OpenApiTests\ClientIdGenerationModes\GeneratedSwagger\swagger.g.json">
<Namespace>OpenApiNSwagEndToEndTests.ClientIdGenerationModes.GeneratedCode</Namespace>
<ClassName>ClientIdGenerationModesClient</ClassName>
<OutputPath>ClientIdGenerationModesClient.cs</OutputPath>
<CodeGenerator>NSwagCSharp</CodeGenerator>
<Options>/ClientClassAccessModifier:internal /GenerateExceptionClasses:false /AdditionalNamespaceUsages:JsonApiDotNetCore.OpenApi.Client.NSwag /GenerateNullableReferenceTypes:true</Options>
</OpenApiReference>
<OpenApiReference Include="..\OpenApiTests\Headers\GeneratedSwagger\swagger.g.json">
<Namespace>OpenApiNSwagEndToEndTests.Headers.GeneratedCode</Namespace>
<ClassName>HeadersClient</ClassName>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using TestBuildingBlocks;

namespace OpenApiTests.ClientIdGenerationModes;

[UsedImplicitly(ImplicitUseTargetFlags.Members)]
public sealed class ClientIdGenerationModesDbContext(DbContextOptions<ClientIdGenerationModesDbContext> options) : TestableDbContext(options)
{
public DbSet<Player> Players => Set<Player>();
public DbSet<Game> Games => Set<Game>();
public DbSet<PlayerGroup> PlayerGroups => Set<PlayerGroup>();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Bogus;
using JetBrains.Annotations;
using TestBuildingBlocks;

// @formatter:wrap_chained_method_calls chop_if_long
// @formatter:wrap_before_first_method_call true

namespace OpenApiTests.ClientIdGenerationModes;

[UsedImplicitly(ImplicitUseTargetFlags.Members)]
public sealed class ClientIdGenerationModesFakers : FakerContainer
{
private readonly Lazy<Faker<Player>> _lazyPlayerFaker = new(() => new Faker<Player>()
.UseSeed(GetFakerSeed())
.RuleFor(player => player.UserName, faker => faker.Person.UserName));

private readonly Lazy<Faker<Game>> _lazyGameFaker = new(() => new Faker<Game>()
.UseSeed(GetFakerSeed())
.RuleFor(game => game.Title, faker => faker.Commerce.ProductName())
.RuleFor(game => game.PurchasePrice, faker => faker.Finance.Amount(1, 80)));

private readonly Lazy<Faker<PlayerGroup>> _lazyGroupFaker = new(() => new Faker<PlayerGroup>()
.UseSeed(GetFakerSeed())
.RuleFor(playerGroup => playerGroup.Name, faker => faker.Person.Company.Name));

public Faker<Player> Player => _lazyPlayerFaker.Value;
public Faker<Game> Game => _lazyGameFaker.Value;
public Faker<PlayerGroup> Group => _lazyGroupFaker.Value;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System.Text.Json;
using TestBuildingBlocks;
using Xunit;

namespace OpenApiTests.ClientIdGenerationModes;

public sealed class ClientIdGenerationModesTests
: IClassFixture<OpenApiTestContext<OpenApiStartup<ClientIdGenerationModesDbContext>, ClientIdGenerationModesDbContext>>
{
private readonly OpenApiTestContext<OpenApiStartup<ClientIdGenerationModesDbContext>, ClientIdGenerationModesDbContext> _testContext;

public ClientIdGenerationModesTests(OpenApiTestContext<OpenApiStartup<ClientIdGenerationModesDbContext>, ClientIdGenerationModesDbContext> testContext)
{
_testContext = testContext;

testContext.UseController<PlayersController>();
testContext.UseController<GamesController>();
testContext.UseController<PlayerGroupsController>();

testContext.SwaggerDocumentOutputDirectory = $"{GetType().Namespace!.Replace('.', '/')}/GeneratedSwagger";
}

[Fact]
public async Task Schema_property_for_ID_is_required_in_post_request()
{
// Act
JsonElement document = await _testContext.GetSwaggerDocumentAsync();

// Assert
document.Should().ContainPath("components.schemas.playerDataInPostRequest").With(dataElement =>
{
dataElement.Should().ContainPath("required").With(requiredElement =>
{
requiredElement.Should().ContainArrayElement("id");
});

dataElement.Should().ContainPath("properties.id");
});
}

[Fact]
public async Task Schema_property_for_ID_is_optional_in_post_request()
{
// Act
JsonElement document = await _testContext.GetSwaggerDocumentAsync();

// Assert
document.Should().ContainPath("components.schemas.gameDataInPostRequest").With(dataElement =>
{
dataElement.Should().ContainPath("required").With(requiredElement =>
{
requiredElement.Should().NotContainArrayElement("id");
});

dataElement.Should().ContainPath("properties.id");
});
}

[Fact]
public async Task Schema_property_for_ID_is_omitted_in_post_request()
{
// Act
JsonElement document = await _testContext.GetSwaggerDocumentAsync();

// Assert
document.Should().ContainPath("components.schemas.playerGroupDataInPostRequest").With(dataElement =>
{
dataElement.Should().ContainPath("required").With(requiredElement =>
{
requiredElement.Should().NotContainArrayElement("id");
});

dataElement.Should().NotContainPath("properties.id");
});
}
}
19 changes: 19 additions & 0 deletions test/OpenApiTests/ClientIdGenerationModes/Game.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Controllers;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;

namespace OpenApiTests.ClientIdGenerationModes;

[UsedImplicitly(ImplicitUseTargetFlags.Members)]
[Resource(ControllerNamespace = "OpenApiTests.ClientIdGenerationModes", ClientIdGeneration = ClientIdGenerationMode.Allowed,
GenerateControllerEndpoints = JsonApiEndpoints.Post)]
public sealed class Game : Identifiable<Guid>
{
[Attr]
public string Title { get; set; } = null!;

[Attr]
public decimal PurchasePrice { get; set; }
}
Loading