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

Feature add crud operations for products #255

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
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
6 changes: 3 additions & 3 deletions IGroceryStore.sln.DotSettings.user
Original file line number Diff line number Diff line change
@@ -4,11 +4,11 @@
<PhysicalFolder Path="/Users/adrianfranczak/.nuget/packages/opentelemetry.instrumentation.http/1.0.0-rc9.5" Loaded="True" />
<PhysicalFolder Path="/Users/adrianfranczak/.nuget/packages/opentelemetry.instrumentation.http/1.0.0-rc9.6" Loaded="True" />
&lt;/AssemblyExplorer&gt;</s:String>
<s:String x:Key="/Default/Environment/Highlighting/HighlightingSourceSnapshotLocation/@EntryValue">/Users/adrianfranczak/Library/Caches/JetBrains/Rider2022.2/resharper-host/temp/Rider/vAny/CoverageData/_IGroceryStore.1213299661/Snapshot/snapshot.utdcvr</s:String>


<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=bb40838d_002De9ff_002D4741_002Da625_002D9ff5d7dda92b/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="All tests from &amp;lt;tests&amp;gt;" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;
&lt;Project Location="/Users/adrianfranczak/Repos/Private/IGroceryStore" Presentation="&amp;lt;tests&amp;gt;" /&gt;

<s:String x:Key="/Default/Environment/UnitTesting/UnitTestSessionStore/Sessions/=bb40838d_002De9ff_002D4741_002Da625_002D9ff5d7dda92b/@EntryIndexedValue">&lt;SessionState ContinuousTestingMode="0" IsActive="True" Name="All tests from &amp;lt;tests&amp;gt;" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"&gt;&#xD;
&lt;Project Location="\Users\adrianfranczak\Repos\Private\IGroceryStore" Presentation="&amp;lt;tests&amp;gt;" /&gt;&#xD;
&lt;/SessionState&gt;</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Respawner/@EntryIndexedValue">True</s:Boolean>

2 changes: 1 addition & 1 deletion src/API/Middlewares/ExceptionMiddleware.cs
Original file line number Diff line number Diff line change
@@ -66,4 +66,4 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)
}
private static string ToUnderscoreCase(string value)
=> string.Concat(value.Select((x, i) => i > 0 && char.IsUpper(x) && !char.IsUpper(value[i-1]) ? $"_{x}" : x.ToString())).ToLower();
}
}
8 changes: 4 additions & 4 deletions src/API/Program.cs
Original file line number Diff line number Diff line change
@@ -25,10 +25,10 @@
}

//AWS
if (!builder.Environment.IsDevelopment() && !builder.Environment.IsTestEnvironment())
{
builder.Configuration.AddSystemsManager("/Production/IGroceryStore", TimeSpan.FromSeconds(30));
}
// if (!builder.Environment.IsDevelopment() && !builder.Environment.IsTestEnvironment())
// {
// builder.Configuration.AddSystemsManager("/Production/IGroceryStore", TimeSpan.FromSeconds(30));
// }

//DateTime
builder.Services.AddSingleton<DateTimeService>();
2 changes: 1 addition & 1 deletion src/API/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@
"profiles": {
"Postman": {
"commandName": "Project",
"launchBrowser": false,
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
2 changes: 1 addition & 1 deletion src/API/appsettings.json
Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@
]
},
"ElasticConfiguration": {
"Uri": "foo"
"Uri": "http://localhost:9200"
},
"Postgres": {
"ConnectionString": "foo",
4 changes: 4 additions & 0 deletions src/Baskets/Baskets.Core/Baskets.Core.csproj
Original file line number Diff line number Diff line change
@@ -27,4 +27,8 @@
<PackageReference Include="MongoDB.Driver" Version="2.18.0" />
</ItemGroup>

<ItemGroup>
<Folder Include="Persistence" />
</ItemGroup>

</Project>
3 changes: 3 additions & 0 deletions src/Products/Products.Contracts/Events/ProductUpdated.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace IGroceryStore.Products.Contracts.Events;

public record class ProductUpdated(ulong Id, string Name);
Original file line number Diff line number Diff line change
@@ -22,7 +22,7 @@ public class UpdateCategoryEndpoint : IEndpoint
{
public void RegisterEndpoint(IEndpointRouteBuilder endpoints) =>
endpoints.MapPut<UpdateCategory>("api/categories/{id}")
.AddEndpointFilter<ValidationFilter<UpdateCategory.UpdateCategoryBody>>()
.AddEndpointFilter<ValidationFilter<UpdateCategory>>()
.WithTags(SwaggerTags.Products)
.Produces(202)
.Produces(400);
@@ -55,11 +55,11 @@ await _productsDbContext.Categories
}
}

internal class UpdateCategoryValidator : AbstractValidator<UpdateCategory.UpdateCategoryBody>
internal class UpdateCategoryValidator : AbstractValidator<UpdateCategory>
{
public UpdateCategoryValidator()
{
RuleFor(x => x.Name)
RuleFor(x => x.Body.Name)
.MinimumLength(3)
.NotEmpty();
}
Original file line number Diff line number Diff line change
@@ -11,7 +11,6 @@
using IGroceryStore.Shared.Services;
using IGroceryStore.Shared.Validation;
using MassTransit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
@@ -32,9 +31,11 @@ public class CreateProductEndpoint : IEndpoint
{
public void RegisterEndpoint(IEndpointRouteBuilder endpoints) =>
endpoints.MapPost<CreateProduct>("api/products")
.RequireAuthorization()
.AddEndpointFilter<ValidationFilter<CreateProduct.CreateProductBody>>()
.WithTags(SwaggerTags.Products);
//.RequireAuthorization()
.AddEndpointFilter<ValidationFilter<CreateProduct>>()
.WithTags(SwaggerTags.Products)
.Produces(400)
.Produces(202);
}

internal class CreateProductHandler : ICommandHandler<CreateProduct, IResult>
@@ -81,32 +82,32 @@ public async Task<IResult> HandleAsync(CreateProduct command, CancellationToken
}
}

internal class CreateProductValidator : AbstractValidator<CreateProduct.CreateProductBody>
internal class CreateProductValidator : AbstractValidator<CreateProduct>
{
public CreateProductValidator()
{
RuleFor(x => x.Name)
RuleFor(x => x.Body.Name)
.NotEmpty()
.MinimumLength(3);

RuleFor(x => x.Quantity)
RuleFor(x => x.Body.Quantity)
.NotNull()
.DependentRules(() =>
{
RuleFor(x => x.Quantity.Amount)
RuleFor(x => x.Body.Quantity.Amount)
.GreaterThan(0);

RuleFor(x => x.Quantity.Unit)
RuleFor(x => x.Body.Quantity.Unit)
.NotEmpty();
});

RuleFor(x => x.BrandId)
RuleFor(x => x.Body.BrandId)
.NotEmpty();

RuleFor(x => x.CountryId)
RuleFor(x => x.Body.CountryId)
.NotEmpty();

RuleFor(x => x.CategoryId)
RuleFor(x => x.Body.CategoryId)
.NotEmpty();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using IGroceryStore.Products.Exceptions;
using IGroceryStore.Products.Persistence.Contexts;
using IGroceryStore.Shared.Abstraction.Commands;
using IGroceryStore.Shared.Abstraction.Common;
using IGroceryStore.Shared.Abstraction.Constants;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;

namespace IGroceryStore.Products.Core.Features.Products.Commands;

internal record DeleteProduct(ulong Id) : IHttpCommand;

public class DeleteProductEndpoint : IEndpoint
{
public void RegisterEndpoint(IEndpointRouteBuilder endpoints) =>
endpoints.MapDelete<DeleteProduct>("api/products/{id}")
//.RequireAuthorization()
.WithTags(SwaggerTags.Products)
.Produces(204)
.Produces(400);

}

internal class DeleteProductHandler : ICommandHandler<DeleteProduct, IResult>
{
private readonly ProductsDbContext _productsDbContext;

public DeleteProductHandler(ProductsDbContext productsDbContext)
{
_productsDbContext = productsDbContext;
}

public async Task<IResult> HandleAsync(DeleteProduct command, CancellationToken cancellationToken = default)
{
var products = await _productsDbContext.Products.ToListAsync();

var product =
await _productsDbContext.Products.FirstOrDefaultAsync(x => x.Id.Equals(command.Id), cancellationToken);

if (product is null) throw new ProductNotFoundException(command.Id);

_productsDbContext.Products.Remove(product);
await _productsDbContext.SaveChangesAsync(cancellationToken);

return Results.NoContent();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,58 @@
namespace IGroceryStore.Products.Features.Products.Commands;
using IGroceryStore.Products.Contracts.Events;
using IGroceryStore.Products.Exceptions;
using IGroceryStore.Products.Persistence.Contexts;
using IGroceryStore.Shared.Abstraction.Commands;
using IGroceryStore.Shared.Abstraction.Common;
using IGroceryStore.Shared.Abstraction.Constants;
using MassTransit;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;

internal class UpdateDetails
namespace IGroceryStore.Products.Features.Products.Commands;

internal record UpdateDetails(UpdateDetails.UpdateDetailsBody DetailsBody, ulong Id) : IHttpCommand
{
internal record UpdateDetailsBody(string Name,
string Description
);
}

public class UpdateDetailsEndpoint : IEndpoint
{
public void RegisterEndpoint(IEndpointRouteBuilder endpoints)
=> endpoints.MapPut<UpdateDetails>("api/products")
.WithTags(SwaggerTags.Products)
.Produces(204)
.Produces(400);
}

internal class UpdateDetailsHandler : ICommandHandler<UpdateDetails, IResult>
{
private readonly ProductsDbContext _context;
private readonly IBus _bus;

public UpdateDetailsHandler(ProductsDbContext context, IBus bus)
{
_context = context;
_bus = bus;
}

public async Task<IResult> HandleAsync(UpdateDetails command, CancellationToken cancellationToken = default)
{
var product = await _context.Products.FirstOrDefaultAsync(x => x.Id.Equals(command.Id), cancellationToken);

if (product is null) throw new ProductNotFoundException(command.Id);

var (name, description) = command.DetailsBody;

product.Name = name;
product.Description = description;
_context.Update(product);
await _context.SaveChangesAsync(cancellationToken);

await _bus.Publish(new ProductUpdated(command.Id, name), cancellationToken);

return Results.NoContent();
}
}
16 changes: 10 additions & 6 deletions src/Products/Products.Core/Products.Core.csproj
Original file line number Diff line number Diff line change
@@ -10,18 +10,22 @@
</PropertyGroup>

<ItemGroup>
<InternalsVisibleTo Include="$(AssemblyName).UnitTests"/>
<InternalsVisibleTo Include="$(AssemblyName).IntegrationTests"/>
<InternalsVisibleTo Include="$(AssemblyName).UnitTests" />
<InternalsVisibleTo Include="$(AssemblyName).IntegrationTests" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\Shared\Shared\Shared.csproj"/>
<ProjectReference Include="..\Products.Contracts\Products.Contracts.csproj"/>
<ProjectReference Include="..\..\Shared\Shared\Shared.csproj" />
<ProjectReference Include="..\Products.Contracts\Products.Contracts.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="7.0.0-rc.2.22476.2"/>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0-rc.2"/>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="7.0.0-rc.2.22476.2" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0-rc.2" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Products.IntegrationTests" />
</ItemGroup>

</Project>
2 changes: 1 addition & 1 deletion src/Products/Products.Core/modulesettings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"Products": {
"ModuleEnabled": false
"ModuleEnabled": true
}
}
20 changes: 10 additions & 10 deletions src/Users/Users.Core/Users.Core.csproj
Original file line number Diff line number Diff line change
@@ -10,22 +10,22 @@
</PropertyGroup>

<ItemGroup>
<InternalsVisibleTo Include="$(AssemblyName).UnitTests"/>
<InternalsVisibleTo Include="$(AssemblyName).IntegrationTests"/>
<InternalsVisibleTo Include="$(AssemblyName).UnitTests" />
<InternalsVisibleTo Include="$(AssemblyName).IntegrationTests" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Users.Contracts\Users.Contracts.csproj"/>
<ProjectReference Include="..\..\Shared\Shared\Shared.csproj"/>
<ProjectReference Include="..\Users.Contracts\Users.Contracts.csproj" />
<ProjectReference Include="..\..\Shared\Shared\Shared.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.0-rc.2.22476.2"/>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.0-rc.2.22472.11"/>
<PackageReference Include="JWT" Version="10.0.0-beta9"/>
<PackageReference Include="JWT.Extensions.AspNetCore" Version="10.0.0-beta4"/>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3"/>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0-rc.2"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.0-rc.2.22476.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.0-rc.2.22472.11" />
<PackageReference Include="JWT" Version="10.0.0-beta9" />
<PackageReference Include="JWT.Extensions.AspNetCore" Version="10.0.0-beta4" />
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0-rc.2" />
</ItemGroup>

</Project>
24 changes: 24 additions & 0 deletions tests/Products/Products.IntegrationTests/DbConfigExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using DotNet.Testcontainers.Containers;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Products.IntegrationTests;

public static class DbConfigExtensions
{
public static void CleanDbContextOptions<T>(this IServiceCollection services)
where T : DbContext
{
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<T>));
if (descriptor != null) services.Remove(descriptor);
services.RemoveAll(typeof(T));
}

public static void AddPostgresContext<T>(this IServiceCollection services, TestcontainerDatabase dbContainer)
where T : DbContext
{
services.AddDbContext<T>(ctx =>
ctx.UseNpgsql(dbContainer.ConnectionString));
}
}
103 changes: 103 additions & 0 deletions tests/Products/Products.IntegrationTests/ProductApiFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
using Bogus;
using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Configurations;
using DotNet.Testcontainers.Containers;
using IGroceryStore.API;
using IGroceryStore.Products.Contracts.Events;
using IGroceryStore.Products.Persistence.Contexts;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using MassTransit;
using Microsoft.AspNetCore.TestHost;
using IGroceryStore.Shared.Tests.Auth;
using Respawn;
using System.Data.Common;
using IGroceryStore.Shared.Abstraction.Constants;
using System.Security.Claims;
using IGroceryStore.Shared.Services;
using Microsoft.Extensions.DependencyInjection;
using Npgsql;

namespace Products.IntegrationTests;

public class ProductApiFactory : WebApplicationFactory<IApiMarker>, IAsyncLifetime
{
private readonly MockUser _user;
private Respawner _respawner = default!;
private DbConnection _dbConnection = default!;
private readonly TestcontainerDatabase _dbContainer =
new TestcontainersBuilder<PostgreSqlTestcontainer>()
.WithDatabase(new PostgreSqlTestcontainerConfiguration
{
Database = Guid.NewGuid().ToString(),
Username = "postgres",
Password = "postgres"
})
.WithAutoRemove(true)
.WithCleanUp(true)
.Build();

public ProductApiFactory()
{
_user = new MockUser(new Claim(Claims.Name.UserId, "1"),
new Claim(Claims.Name.Expire, DateTimeOffset.UtcNow.AddSeconds(2137).ToUnixTimeSeconds().ToString()));
Randomizer.Seed = new Random(420);
VerifierSettings.ScrubInlineGuids();
}

public HttpClient HttpClient { get; private set; } = default!;

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureLogging(logging => { logging.ClearProviders(); });

builder.UseEnvironment(EnvironmentService.TestEnvironment);

builder.ConfigureServices(services =>
{
services.AddMassTransitTestHarness(x =>
{
x.AddHandler<ProductAdded>(context => context.ConsumeCompleted);
});
});

builder.ConfigureTestServices(services =>
{
//services.CleanDbContextOptions<UsersDbContext>();
services.CleanDbContextOptions<ProductsDbContext>();

//services.AddPostgresContext<UsersDbContext>(_dbContainer);
services.AddPostgresContext<ProductsDbContext>(_dbContainer);

services.AddTestAuthentication();

services.AddSingleton<IMockUser>(_ => _user);
});
}

public async Task InitializeAsync()
{
await _dbContainer.StartAsync();
_dbConnection = new NpgsqlConnection(_dbContainer.ConnectionString);
HttpClient = CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
await InitializeRespawner();
}

public async Task ResetDatabaseAsync() => await _respawner.ResetAsync(_dbConnection);

private async Task InitializeRespawner()
{
await _dbConnection.OpenAsync();
_respawner = await Respawner.CreateAsync(_dbConnection, new RespawnerOptions()
{
DbAdapter = DbAdapter.Postgres,
SchemasToInclude = new[] { "IGroceryStore.Products" },
});
}

async Task IAsyncLifetime.DisposeAsync()
{
await _dbContainer.DisposeAsync();
}
}
8 changes: 8 additions & 0 deletions tests/Products/Products.IntegrationTests/ProductCollection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using Products.IntegrationTests;

namespace IGroceryStore.Products.IntegrationTests;

[CollectionDefinition("ProductCollection")]
public class ProductCollection : ICollectionFixture<ProductApiFactory>
{
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
@@ -10,6 +10,23 @@
<RootNamespace>IGroceryStore.Products.IntegrationTests</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.8.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="7.0.0-rc.2.22476.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0-preview-20221003-04" />
<PackageReference Include="Testcontainers" Version="2.2.0" />
<PackageReference Include="Verify" Version="18.3.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\src\API\API.csproj" />
<ProjectReference Include="..\..\Shared\Shared.csproj" />
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using System.Net;
using System.Net.Http.Json;
using System.Security.Claims;
using Bogus;
using FluentAssertions;
using IGroceryStore.Products.Features.Products.Commands;
using IGroceryStore.Products.IntegrationTests.TestModels;
using IGroceryStore.Products.ReadModels;
using IGroceryStore.Products.ValueObjects;
using IGroceryStore.Shared.Abstraction.Constants;
using IGroceryStore.Shared.Tests.Auth;
using Microsoft.AspNetCore.TestHost;
using Products.IntegrationTests;

namespace IGroceryStore.Products.IntegrationTests.Products;

[UsesVerify]
[Collection("ProductCollection")]
public class CreateProductTests : IClassFixture<ProductApiFactory>, IAsyncLifetime
{
private readonly HttpClient _client;
private readonly Func<Task> _resetDatabase;
private readonly ProductsFakeSeeder _productsFakeSeeder;

public CreateProductTests(ProductApiFactory productApiFactory)
{
_client = productApiFactory.HttpClient;
_resetDatabase = productApiFactory.ResetDatabaseAsync;
productApiFactory
.WithWebHostBuilder(builder =>
builder.ConfigureTestServices(services =>
{
services.RegisterUser(new[]
{
new Claim(Claims.Name.UserId, "1"),
new Claim(Claims.Name.Expire,
DateTimeOffset.UtcNow.AddSeconds(2137).ToUnixTimeSeconds().ToString())
});
})); // override authorized user;

_productsFakeSeeder = new ProductsFakeSeeder(productApiFactory);
//productApiFactory.SeedProductDb();
}

[Fact]
public async Task CreateProduct_WhenDataIsValid()
{
// Arrange
await _productsFakeSeeder.SeedData();
var createProduct = GetFakeCreateProduct();

// Act
var response = await _client.PostAsJsonAsync($"api/products", createProduct);

// Assert
response.StatusCode.Should().Be(HttpStatusCode.Accepted);
}

[Fact]
public async Task CreateProduct_WhenCategoryNotExists_ShouldReturnNotFound()
{
// Arrange
await _productsFakeSeeder.SeedData();
var createProduct = GetFakeCreateProduct();

await _client.DeleteAsync($"api/categories/{createProduct.CategoryId}");

// Act
var response = await _client.PostAsJsonAsync($"api/products", createProduct);

// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}

private CreateProduct.CreateProductBody GetFakeCreateProduct()
{
var units = new[] { Unit.Centimeter, Unit.Gram, Unit.Milliliter, Unit.Piece };

var brandsIds = TestBrands.Brands
.Select(x => x.Id.Id)
.ToList();

var countriesIds = TestCountries.Countries
.Select(x => x.Id.Id)
.ToList();

var categoriesIds = TestCategories.Categories
.Select(x => x.Id.Id)
.ToList();

var faker = new Faker();

var body = new CreateProduct.CreateProductBody(
faker.Commerce.ProductName(),
new QuantityReadModel(faker.Random.UInt(1, 20) * 100, faker.PickRandom(units)),
faker.PickRandom(brandsIds),
faker.PickRandom(countriesIds),
faker.PickRandom(categoriesIds)
);

return body;
}

public Task InitializeAsync() => Task.CompletedTask;
public Task DisposeAsync() => _resetDatabase();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System.Net;
using FluentAssertions;
using Microsoft.AspNetCore.TestHost;
using IGroceryStore.Shared.Tests.Auth;
using System.Security.Claims;
using IGroceryStore.Shared.Abstraction.Constants;
using IGroceryStore.Products.IntegrationTests;
using IGroceryStore.Products.IntegrationTests.TestModels;

namespace Products.IntegrationTests.Products;

[UsesVerify]
[Collection("ProductCollection")]
public class DeleteProductsTests : IClassFixture<ProductApiFactory>, IAsyncLifetime
{
private readonly HttpClient _client;
private readonly Func<Task> _resetDatabase;
private readonly ProductsFakeSeeder _productsFakeSeeder;

public DeleteProductsTests(ProductApiFactory productApiFactory)
{
_client = productApiFactory.HttpClient;
_resetDatabase = productApiFactory.ResetDatabaseAsync;
productApiFactory
.WithWebHostBuilder(builder =>
builder.ConfigureTestServices(services =>
{
services.RegisterUser(new[]
{
new Claim(Claims.Name.UserId, "1"),
new Claim(Claims.Name.Expire,
DateTimeOffset.UtcNow.AddSeconds(2137).ToUnixTimeSeconds().ToString())
});
})); // override authorized user;

_productsFakeSeeder = new ProductsFakeSeeder(productApiFactory);
}

[Fact]
public async Task DeleteProduct_WhenProductExists()
{
// Arrange
await _productsFakeSeeder.SeedData();
var product = TestProducts.Product;

// Act
var response = await _client.DeleteAsync($"api/products/{product.Id.Value}");

// Assert
response.StatusCode.Should().Be(HttpStatusCode.NoContent);
}

[Fact]
public async Task ReturnNotFound_WhenProductNotExists()
{
// Arrange
var product = TestProducts.Product;

// Act
var response = await _client.DeleteAsync($"api/products/{product.Id.Value}");

// Assert
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}

public Task InitializeAsync() => Task.CompletedTask;
public Task DisposeAsync() => _resetDatabase();
}
30 changes: 30 additions & 0 deletions tests/Products/Products.IntegrationTests/ProductsFakeSeeder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using IGroceryStore.Products.IntegrationTests.TestModels;
using IGroceryStore.Products.Persistence.Contexts;
using Microsoft.Extensions.DependencyInjection;
using Products.IntegrationTests;

namespace IGroceryStore.Products.IntegrationTests;

public class ProductsFakeSeeder
{
private ProductApiFactory _productApiFactory;

public ProductsFakeSeeder(ProductApiFactory productApiFactory)
{
_productApiFactory = productApiFactory;
}

public async Task SeedData()
{
//await _productApiFactory.ResetDatabaseAsync();

using var scope = _productApiFactory.Services.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ProductsDbContext>();

await context.Countries.AddRangeAsync(TestCountries.Countries);
await context.Brands.AddRangeAsync(TestBrands.Brands);
await context.Categories.AddRangeAsync(TestCategories.Categories);
await context.Products.AddRangeAsync(TestProducts.Products);
await context.SaveChangesAsync();
}
}
28 changes: 28 additions & 0 deletions tests/Products/Products.IntegrationTests/TestModels/TestBrands.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Bogus;
using IGroceryStore.Products.Entities;
using IGroceryStore.Products.ValueObjects;

namespace IGroceryStore.Products.IntegrationTests.TestModels;

internal static class TestBrands
{
private static readonly Faker<Brand> ProductGenerator = new BrandFaker();

public static readonly List<Brand> Brands = ProductGenerator.Generate(10);
public static readonly Brand Brand = Brands.First();

private sealed class BrandFaker : Faker<Brand>
{
public BrandFaker()
{
CustomInstantiator(ResolveConstructor);
}

private Brand ResolveConstructor(Faker faker)
{
var brand = new Brand { Id = new BrandId((ulong)faker.UniqueIndex), Name = faker.Company.CompanyName() };

return brand;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Bogus;
using IGroceryStore.Products.Entities;
using IGroceryStore.Products.Features.Categories.Commands;
using IGroceryStore.Products.ValueObjects;

namespace IGroceryStore.Products.IntegrationTests.TestModels;

internal static class TestCategories
{
private static readonly Faker<Category> CategoryGenerator = new CategoryFaker();

public static readonly List<Category> Categories = CategoryGenerator.Generate(10);
public static readonly Category Category = Categories.First();

private sealed class CategoryFaker : Faker<Category>
{
public CategoryFaker()
{
CustomInstantiator(ResolveConstructor);
}

private Category ResolveConstructor(Faker faker)
{
return new Category
{
Id = new CategoryId((ulong)faker.UniqueIndex),
Name = faker.Commerce.Categories(1).First()
};
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Bogus;
using IGroceryStore.Products.Entities;
using IGroceryStore.Products.ValueObjects;

namespace IGroceryStore.Products.IntegrationTests.TestModels;

internal static class TestCountries
{
private static readonly Faker<Country> CountryGenerator = new CountryFaker();

public static readonly List<Country> Countries = CountryGenerator.Generate(10);
public static readonly Country Country = Countries.First();

private sealed class CountryFaker : Faker<Country>
{
public CountryFaker()
{
CustomInstantiator(ResolveConstructor);
}

private Country ResolveConstructor(Faker faker)
{
return new Country
{
Id = new CountryId((ulong)faker.UniqueIndex),
Name = faker.Address.Country(),
Code = faker.Address.CountryCode()
};
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
using Bogus;
using IGroceryStore.Products.Entities;
using IGroceryStore.Products.ValueObjects;
using IGroceryStore.Shared.ValueObjects;

namespace IGroceryStore.Products.IntegrationTests.TestModels;

internal static class TestProducts
{
private static readonly Faker<Product> CreateProductGenerator = new ProductFaker();

public static readonly List<Product> Products = CreateProductGenerator.Generate(10);
public static readonly Product Product = Products.First();

private sealed class ProductFaker : Faker<Product>
{
public ProductFaker()
{
CustomInstantiator(ResolveConstructor);
}

private Product ResolveConstructor(Faker faker)
{
var units = new[] { Unit.Centimeter, Unit.Gram, Unit.Milliliter, Unit.Piece };

return new Product
{
Id = new ProductId(faker.Random.UInt()),
Name = new ProductName(faker.Commerce.ProductName()),
Description = new Description(faker.Commerce.ProductDescription()),
Quantity = new Quantity(faker.Random.UInt(1, 20) * 100, faker.PickRandom(units)),
CountryId = new CountryId(TestCountries.Country.Id),
CategoryId = new CategoryId(TestCategories.Category.Id),
BrandId = new BrandId(TestBrands.Brand.Id),
ImageUrl = new Uri(faker.Internet.Url()),
BarCode = new BarCode(faker.Random.UInt(100_000_000, 900_000_000).ToString())
};
}
}
}