├── src ├── CF.Customer.Domain │ ├── Services │ │ ├── Interfaces │ │ │ ├── IPasswordHasherService.cs │ │ │ └── ICustomerService.cs │ │ ├── PasswordHasherService.cs │ │ └── CustomerService.cs │ ├── CF.Customer.Domain.csproj │ ├── Entities │ │ ├── Customer.cs │ │ └── CustomerExtensions.cs │ ├── Models │ │ ├── Pagination.cs │ │ └── CustomerFilter.cs │ ├── Repositories │ │ ├── ICustomerRepository.cs │ │ └── IRepositoryBase.cs │ └── Exceptions │ │ ├── ValidationException.cs │ │ └── EntityNotFoundException.cs ├── CF.IntegrationTest │ ├── Models │ │ └── ErrorResponse.cs │ ├── Seeds │ │ └── CustomerSeed.cs │ ├── CF.IntegrationTest.csproj │ ├── RateLimitingIntegrationTest.cs │ ├── ApiVersioningIntegrationTest.cs │ ├── Factories │ │ └── CustomWebApplicationFactory.cs │ ├── HealthCheckIntegrationTest.cs │ └── CustomerIntegrationTest.cs ├── CF.Customer.Application │ ├── Dtos │ │ ├── CustomerResponseDto.cs │ │ ├── PaginationDto.cs │ │ ├── CustomerFilterDto.cs │ │ └── CustomerRequestDto.cs │ ├── CF.Customer.Application.csproj │ ├── Mappers │ │ └── ICustomerMapper.cs │ └── Facades │ │ ├── Interfaces │ │ └── ICustomerFacade.cs │ │ └── CustomerFacade.cs ├── CF.Api │ ├── .dockerignore │ ├── Dockerfile │ ├── Middleware │ │ ├── LogResponseMiddleware.cs │ │ ├── LogExceptionMiddleware.cs │ │ └── LogRequestMiddleware.cs │ ├── docker-compose.yml │ ├── Helpers │ │ └── ControllerHelper.cs │ ├── Properties │ │ └── launchSettings.json │ ├── CF.Api.csproj │ ├── Filters │ │ └── ExceptionFilter.cs │ ├── appsettings.json │ ├── appsettings.Development.json │ ├── Controllers │ │ └── CustomerController.cs │ └── Program.cs ├── CF.Customer.Infrastructure │ ├── CF.Customer.Infrastructure.csproj │ ├── DbContext │ │ └── CustomerContext.cs │ ├── Mappers │ │ └── CustomerMapper.cs │ └── Repositories │ │ ├── RepositoryBase.cs │ │ └── CustomerRepository.cs ├── CF.Migrations │ ├── CF.Migrations.csproj │ └── Migrations │ │ ├── 20240108231037_InitialMigration.cs │ │ ├── CustomerContextModelSnapshot.cs │ │ └── 20240108231037_InitialMigration.Designer.cs ├── CF.Api.UnitTest │ ├── CF.Api.UnitTest.csproj │ └── CustomerControllerTest.cs └── CF.Customer.UnitTest │ ├── CF.Customer.UnitTest.csproj │ ├── Domain │ ├── Services │ │ ├── PasswordHasherTest.cs │ │ └── CustomerServiceTest.cs │ └── Entities │ │ └── CustomerTest.cs │ ├── Infrastructure │ ├── Mappers │ │ └── CustomerMapperTest.cs │ └── Repositories │ │ └── CustomerRepositoryTest.cs │ └── Application │ └── Facades │ └── CustomerFacadeTest.cs ├── .github ├── workflows │ ├── dotnet-core.yml │ └── codeql-analysis.yml └── dependabot.yml ├── README.md ├── CF.sln └── .gitignore /src/CF.Customer.Domain/Services/Interfaces/IPasswordHasherService.cs: -------------------------------------------------------------------------------- 1 | namespace CF.Customer.Domain.Services.Interfaces; 2 | 3 | public interface IPasswordHasherService 4 | { 5 | string Hash(string password); 6 | 7 | bool Verify(string password, string hash); 8 | } -------------------------------------------------------------------------------- /src/CF.IntegrationTest/Models/ErrorResponse.cs: -------------------------------------------------------------------------------- 1 | namespace CF.IntegrationTest.Models; 2 | 3 | internal class ErrorResponse 4 | { 5 | public string Type { get; set; } 6 | public string Title { get; set; } 7 | public int Status { get; set; } 8 | public string TraceId { get; set; } 9 | public dynamic Errors { get; set; } 10 | } -------------------------------------------------------------------------------- /src/CF.Customer.Application/Dtos/CustomerResponseDto.cs: -------------------------------------------------------------------------------- 1 | namespace CF.Customer.Application.Dtos; 2 | 3 | public record CustomerResponseDto 4 | { 5 | public long Id { get; set; } 6 | public string Email { get; set; } 7 | public string FirstName { get; set; } 8 | public string Surname { get; set; } 9 | public string FullName { get; set; } 10 | } -------------------------------------------------------------------------------- /src/CF.Customer.Application/Dtos/PaginationDto.cs: -------------------------------------------------------------------------------- 1 | namespace CF.Customer.Application.Dtos; 2 | 3 | public record PaginationDto where TDto : class 4 | { 5 | public int CurrentPage { get; set; } 6 | public int Count { get; set; } 7 | public int PageSize { get; set; } 8 | public int TotalPages { get; set; } 9 | public List Result { get; set; } 10 | } -------------------------------------------------------------------------------- /src/CF.Api/.dockerignore: -------------------------------------------------------------------------------- 1 | **/.dockerignore 2 | **/.env 3 | **/.git 4 | **/.gitignore 5 | **/.vs 6 | **/.vscode 7 | **/*.*proj.user 8 | **/azds.yaml 9 | **/charts 10 | **/bin 11 | **/obj 12 | **/Dockerfile 13 | **/Dockerfile.develop 14 | **/docker-compose.yml 15 | **/docker-compose.*.yml 16 | **/*.dbmdl 17 | **/*.jfm 18 | **/secrets.dev.yaml 19 | **/values.dev.yaml 20 | **/.toolstarget -------------------------------------------------------------------------------- /src/CF.Customer.Domain/CF.Customer.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net10.0 4 | enable 5 | latest 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/CF.Customer.Application/CF.Customer.Application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net10.0 4 | enable 5 | latest 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Entities/Customer.cs: -------------------------------------------------------------------------------- 1 | namespace CF.Customer.Domain.Entities; 2 | 3 | public class Customer 4 | { 5 | public long Id { get; set; } 6 | public DateTime Created { get; set; } 7 | public string Email { get; set; } 8 | public string FirstName { get; set; } 9 | public string Password { get; set; } 10 | public string Surname { get; set; } 11 | public DateTime? Updated { get; set; } 12 | } -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Models/Pagination.cs: -------------------------------------------------------------------------------- 1 | namespace CF.Customer.Domain.Models; 2 | 3 | public class Pagination where T : class 4 | { 5 | public int CurrentPage { get; set; } = 1; 6 | public int Count { get; set; } 7 | public int PageSize { get; set; } = 10; 8 | public int TotalPages => PageSize > 0 ? (int)Math.Ceiling(decimal.Divide(Count, PageSize)) : 1; 9 | public List Result { get; set; } = []; 10 | } -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Models/CustomerFilter.cs: -------------------------------------------------------------------------------- 1 | namespace CF.Customer.Domain.Models; 2 | 3 | public class CustomerFilter 4 | { 5 | public long Id { get; set; } 6 | public string Email { get; set; } 7 | public string FirstName { get; set; } 8 | public string Surname { get; set; } 9 | public int CurrentPage { get; set; } = 1; 10 | public int PageSize { get; set; } = 10; 11 | public string OrderBy { get; set; } = "firstName"; 12 | public string SortBy { get; set; } = "asc"; 13 | } -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Services/PasswordHasherService.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Domain.Services.Interfaces; 2 | using Crypt = BCrypt.Net.BCrypt; 3 | 4 | namespace CF.Customer.Domain.Services; 5 | 6 | public class PasswordHasherService : IPasswordHasherService 7 | { 8 | public string Hash(string password) 9 | { 10 | return Crypt.HashPassword(password); 11 | } 12 | 13 | public bool Verify(string password, string hash) 14 | { 15 | return Crypt.Verify(password, hash); 16 | } 17 | } -------------------------------------------------------------------------------- /src/CF.Customer.Application/Dtos/CustomerFilterDto.cs: -------------------------------------------------------------------------------- 1 | namespace CF.Customer.Application.Dtos; 2 | 3 | public record CustomerFilterDto 4 | { 5 | public long Id { get; set; } 6 | public string Email { get; set; } 7 | public string FirstName { get; set; } 8 | public string Surname { get; set; } 9 | public int CurrentPage { get; set; } = 1; 10 | public int PageSize { get; set; } = 10; 11 | public string OrderBy { get; set; } = "firstName"; 12 | public string SortBy { get; set; } = "asc"; 13 | } -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Repositories/ICustomerRepository.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Domain.Models; 2 | 3 | namespace CF.Customer.Domain.Repositories; 4 | 5 | public interface ICustomerRepository : IRepositoryBase 6 | { 7 | Task CountByFilterAsync(CustomerFilter filter, CancellationToken cancellationToken); 8 | Task GetByFilterAsync(CustomerFilter filter, CancellationToken cancellationToken); 9 | Task> GetListByFilterAsync(CustomerFilter filter, CancellationToken cancellationToken); 10 | } -------------------------------------------------------------------------------- /src/CF.Customer.Application/Mappers/ICustomerMapper.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Application.Dtos; 2 | using CF.Customer.Domain.Models; 3 | 4 | namespace CF.Customer.Application.Mappers; 5 | 6 | public interface ICustomerMapper 7 | { 8 | Domain.Entities.Customer MapToCustomer(CustomerRequestDto dto); 9 | CustomerResponseDto MapToCustomerResponseDto(Domain.Entities.Customer customer); 10 | CustomerFilter MapToCustomerFilter(CustomerFilterDto dto); 11 | PaginationDto MapToPaginationDto(Pagination pagination); 12 | } -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Exceptions/ValidationException.cs: -------------------------------------------------------------------------------- 1 | namespace CF.Customer.Domain.Exceptions; 2 | 3 | /// 4 | /// Thrown when an entity cannot be found with a given id from the data layer 5 | /// 6 | public class ValidationException : Exception 7 | { 8 | public ValidationException() 9 | { 10 | } 11 | 12 | public ValidationException(string message) : base(message) 13 | { 14 | } 15 | 16 | public ValidationException(string message, Exception innerException) : base(message, innerException) 17 | { 18 | } 19 | } -------------------------------------------------------------------------------- /src/CF.Api/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base 2 | WORKDIR /app 3 | 4 | FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build 5 | WORKDIR /src 6 | COPY ["CF.Api/CF.Api.csproj", "CF.Api/"] 7 | RUN dotnet restore "CF.Api/CF.Api.csproj" 8 | COPY . . 9 | WORKDIR "/src/CF.Api" 10 | RUN dotnet build "CF.Api.csproj" -c Release -o /app/build 11 | 12 | FROM build AS publish 13 | RUN dotnet publish "CF.Api.csproj" -c Release -o /app/publish 14 | 15 | SFROM base AS final 16 | WORKDIR /app 17 | COPY --from=publish /app/publish . 18 | ENTRYPOINT ["dotnet", "CF.Api.dll"] 19 | -------------------------------------------------------------------------------- /.github/workflows/dotnet-core.yml: -------------------------------------------------------------------------------- 1 | name: .NET 10.0 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: actions/setup-dotnet@v4 17 | with: 18 | dotnet-version: 10.0.x 19 | - name: Install dependencies 20 | run: dotnet restore 21 | - name: Build 22 | run: dotnet build --configuration Release --no-restore 23 | - name: Test 24 | run: dotnet test --no-restore --verbosity normal 25 | -------------------------------------------------------------------------------- /src/CF.Customer.Infrastructure/CF.Customer.Infrastructure.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net10.0 4 | enable 5 | latest 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/CF.Api/Middleware/LogResponseMiddleware.cs: -------------------------------------------------------------------------------- 1 | using CorrelationId.Abstractions; 2 | 3 | namespace CF.Api.Middleware; 4 | 5 | public class LogResponseMiddleware( 6 | RequestDelegate next, 7 | ILogger logger, 8 | ICorrelationContextAccessor correlationContext) 9 | { 10 | public async Task Invoke(HttpContext context) 11 | { 12 | var correlationId = correlationContext.CorrelationContext.CorrelationId; 13 | 14 | logger.LogInformation("StatusCode: {statusCode}. (CorrelationId: {correlationId})", 15 | context.Response.StatusCode, correlationId); 16 | 17 | await next(context); 18 | } 19 | } -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Exceptions/EntityNotFoundException.cs: -------------------------------------------------------------------------------- 1 | namespace CF.Customer.Domain.Exceptions; 2 | 3 | /// 4 | /// Thrown when an entity cannot be found with a given id from the data layer 5 | /// 6 | public class EntityNotFoundException : Exception 7 | { 8 | public EntityNotFoundException() 9 | { 10 | } 11 | 12 | public EntityNotFoundException(string message) : base(message) 13 | { 14 | } 15 | 16 | public EntityNotFoundException(long id) 17 | : base($"Entity with id {id} was not found.") 18 | { 19 | } 20 | 21 | public EntityNotFoundException(string message, Exception innerException) : base(message, innerException) 22 | { 23 | } 24 | } -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Services/Interfaces/ICustomerService.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Domain.Models; 2 | 3 | namespace CF.Customer.Domain.Services.Interfaces; 4 | 5 | public interface ICustomerService 6 | { 7 | Task> 8 | GetListByFilterAsync(CustomerFilter filter, CancellationToken cancellationToken); 9 | 10 | Task GetByFilterAsync(CustomerFilter filter, CancellationToken cancellationToken); 11 | Task UpdateAsync(long id, Entities.Customer customer, CancellationToken cancellationToken); 12 | Task CreateAsync(Entities.Customer customer, CancellationToken cancellationToken); 13 | Task DeleteAsync(long id, CancellationToken cancellationToken); 14 | } -------------------------------------------------------------------------------- /src/CF.IntegrationTest/Seeds/CustomerSeed.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using CF.Customer.Infrastructure.DbContext; 4 | 5 | namespace CF.IntegrationTest.Seeds; 6 | 7 | public class CustomerSeed 8 | { 9 | public static async Task PopulateAsync(CustomerContext dbContext) 10 | { 11 | await dbContext.Customers.AddAsync(new Customer.Domain.Entities.Customer 12 | { 13 | Email = "seed.record@test.com", 14 | Password = "Rgrtgr#$543gfregeg", 15 | FirstName = "Seed", 16 | Surname = "Seed", 17 | Created = DateTime.Now, 18 | Updated = DateTime.Now 19 | }); 20 | 21 | await dbContext.SaveChangesAsync(); 22 | } 23 | } -------------------------------------------------------------------------------- /src/CF.Api/Middleware/LogExceptionMiddleware.cs: -------------------------------------------------------------------------------- 1 | using CorrelationId.Abstractions; 2 | 3 | namespace CF.Api.Middleware; 4 | 5 | public class LogExceptionMiddleware( 6 | RequestDelegate next, 7 | ILogger logger, 8 | ICorrelationContextAccessor correlationContext) 9 | { 10 | public async Task InvokeAsync(HttpContext httpContext) 11 | { 12 | try 13 | { 14 | await next(httpContext); 15 | } 16 | catch (Exception e) 17 | { 18 | var correlationId = correlationContext.CorrelationContext.CorrelationId; 19 | logger.LogError(e, "Unexpected exception. CorrelationId: {correlationId}", correlationId); 20 | throw; 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /src/CF.Api/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | 3 | services: 4 | api: 5 | build: 6 | context: .. 7 | dockerfile: CF.Api/Dockerfile 8 | ports: 9 | - "8888:80" 10 | environment: 11 | - ASPNETCORE_URLS=http://+:80 12 | - ConnectionStrings__DefaultConnection=Server=db;Database=CF;User Id=sa;Password=CF@!1234FC6549;Trusted_Connection=False;TrustServerCertificate=True; 13 | depends_on: 14 | - db 15 | networks: 16 | - app-network 17 | 18 | db: 19 | image: "mcr.microsoft.com/mssql/server:2022-latest" 20 | environment: 21 | SA_PASSWORD: "CF@!1234FC6549" 22 | ACCEPT_EULA: "Y" 23 | networks: 24 | - app-network 25 | 26 | networks: 27 | app-network: 28 | driver: bridge 29 | -------------------------------------------------------------------------------- /src/CF.Customer.Application/Facades/Interfaces/ICustomerFacade.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Application.Dtos; 2 | 3 | namespace CF.Customer.Application.Facades.Interfaces; 4 | 5 | public interface ICustomerFacade 6 | { 7 | Task GetByFilterAsync(CustomerFilterDto filterDto, CancellationToken cancellationToken); 8 | 9 | Task> GetListByFilterAsync(CustomerFilterDto filterDto, 10 | CancellationToken cancellationToken); 11 | 12 | Task CreateAsync(CustomerRequestDto customerRequestDto, CancellationToken cancellationToken); 13 | Task UpdateAsync(long id, CustomerRequestDto customerRequestDto, CancellationToken cancellationToken); 14 | Task DeleteAsync(long id, CancellationToken cancellationToken); 15 | } -------------------------------------------------------------------------------- /src/CF.Api/Helpers/ControllerHelper.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | 3 | namespace CF.Api.Helpers; 4 | 5 | internal static class ControllerHelper 6 | { 7 | public static ProblemDetails CreateProblemDetails(string property, string errorMessage) 8 | { 9 | var error = new KeyValuePair("Errors", new Dictionary> 10 | { 11 | { property, [errorMessage] } 12 | } 13 | ); 14 | 15 | return new ProblemDetails 16 | { 17 | Extensions = { error }, 18 | Title = "An error occurred.", 19 | Status = StatusCodes.Status400BadRequest, 20 | Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1" 21 | }; 22 | } 23 | } -------------------------------------------------------------------------------- /src/CF.Migrations/CF.Migrations.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net10.0 4 | enable 5 | enable 6 | 7 | 8 | 9 | 10 | all 11 | runtime; build; native; contentfiles; analyzers 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![.NET 10.0](https://github.com/leandro-cervelin/cf_api_net_core/actions/workflows/dotnet-core.yml/badge.svg)](https://github.com/leandro-cervelin/cf_api_net_core/actions/workflows/dotnet-core.yml) [![CodeQL .NET 10.0](https://github.com/leandro-cervelin/cf_api_net_core/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/leandro-cervelin/cf_api_net_core/actions/workflows/codeql-analysis.yml) 2 | # .NET 10.0 Example App / API 3 | ## .Net 10.0 API using SQL Server with Entity Framework Core 4 | ## Unit Tests and Integration Tests 5 | ## Docker with Compose 6 | 7 | Docker steps: 8 | 9 | - switch to Linux containers 10 | 11 | from the folder src run the below commands 12 | 13 | - docker-compose -f CF.Api/docker-compose.yml build 14 | - docker-compose -f CF.Api/docker-compose.yml up 15 | 16 | http://localhost:8888/scalar/v1 17 | -------------------------------------------------------------------------------- /src/CF.Api/Middleware/LogRequestMiddleware.cs: -------------------------------------------------------------------------------- 1 | using CorrelationId.Abstractions; 2 | using Microsoft.AspNetCore.Http.Extensions; 3 | 4 | namespace CF.Api.Middleware; 5 | 6 | public class LogRequestMiddleware( 7 | RequestDelegate next, 8 | ILogger logger, 9 | ICorrelationContextAccessor correlationContext) 10 | { 11 | public async Task Invoke(HttpContext context) 12 | { 13 | var url = context.Request.GetDisplayUrl(); 14 | 15 | var correlationId = correlationContext.CorrelationContext.CorrelationId; 16 | 17 | logger.LogInformation( 18 | "Scheme: {scheme}, Host: {host}, Path: {path}, Method: {method}, url: {url}, correlationId: {correlationId}", 19 | context.Request.Scheme, context.Request.Host, context.Request.Path, context.Request.Method, url, 20 | correlationId); 21 | 22 | await next(context); 23 | } 24 | } -------------------------------------------------------------------------------- /src/CF.Api/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:53233", 8 | "sslPort": 44380 9 | } 10 | }, 11 | "profiles": { 12 | "CF.Api": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "scalar/v1", 17 | "applicationUrl": "https://localhost:7242;http://localhost:5242", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "scalar/v1", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "nuget" 9 | directory: "/src/CF.Api.IntegrationTest/" 10 | schedule: 11 | interval: "daily" 12 | - package-ecosystem: "nuget" 13 | directory: "/src/CF.Api/" 14 | schedule: 15 | interval: "daily" 16 | - package-ecosystem: "nuget" 17 | directory: "/src/CF.Customer.Application/" 18 | schedule: 19 | interval: "daily" 20 | - package-ecosystem: "nuget" 21 | directory: "/src/CF.Customer.Domain/" 22 | schedule: 23 | interval: "daily" 24 | - package-ecosystem: "nuget" 25 | directory: "/src/CF.Customer.Infrastructure/" 26 | schedule: 27 | interval: "daily" 28 | - package-ecosystem: "nuget" 29 | directory: "/src/CF.Customer.UnitTest/" 30 | schedule: 31 | interval: "daily" 32 | -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Repositories/IRepositoryBase.cs: -------------------------------------------------------------------------------- 1 | namespace CF.Customer.Domain.Repositories; 2 | 3 | public interface IRepositoryBase : IDisposable where TEntity : class 4 | { 5 | /// 6 | /// This method is async only to allow special value generators, such as the one used by 7 | /// 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database 8 | /// asynchronously. For all other cases the non async method should be used. 9 | /// https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbset-1?view=efcore-3.1#Microsoft_EntityFrameworkCore_DbSet_1_AddAsync__0_System_Threading_CancellationToken_ 10 | /// 11 | Task AddAsync(TEntity entity, CancellationToken cancellationToken); 12 | 13 | void Add(TEntity entity); 14 | Task GetByIdAsync(long id, CancellationToken cancellationToken); 15 | Task> GetAllAsync(CancellationToken cancellationToken); 16 | void Update(TEntity entity); 17 | void Remove(TEntity entity); 18 | Task SaveChangesAsync(CancellationToken cancellationToken); 19 | } -------------------------------------------------------------------------------- /src/CF.Api.UnitTest/CF.Api.UnitTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net10.0 4 | enable 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | all 15 | 16 | 17 | runtime; build; native; contentfiles; analyzers; buildtransitive 18 | all 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/CF.Customer.Infrastructure/DbContext/CustomerContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace CF.Customer.Infrastructure.DbContext; 4 | 5 | public class CustomerContext(DbContextOptions options) 6 | : Microsoft.EntityFrameworkCore.DbContext(options) 7 | { 8 | public DbSet Customers { get; set; } 9 | 10 | protected override void OnModelCreating(ModelBuilder modelBuilder) 11 | { 12 | CustomerModelBuilder(modelBuilder); 13 | } 14 | 15 | private static void CustomerModelBuilder(ModelBuilder modelBuilder) 16 | { 17 | var model = modelBuilder.Entity(); 18 | 19 | model.ToTable("Customer"); 20 | 21 | model.Property(x => x.Email) 22 | .HasMaxLength(100) 23 | .IsRequired(); 24 | 25 | model.HasIndex(x => x.Email) 26 | .IsUnique(); 27 | 28 | model.Property(x => x.FirstName) 29 | .HasMaxLength(100) 30 | .IsRequired(); 31 | 32 | model.Property(x => x.Password) 33 | .HasMaxLength(2000) 34 | .IsRequired(); 35 | 36 | model.Property(x => x.Surname) 37 | .HasMaxLength(100) 38 | .IsRequired(); 39 | } 40 | } -------------------------------------------------------------------------------- /src/CF.Customer.UnitTest/CF.Customer.UnitTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net10.0 4 | enable 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | all 15 | runtime; build; native; contentfiles; analyzers; buildtransitive 16 | 17 | 18 | all 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/CF.IntegrationTest/CF.IntegrationTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net10.0 4 | latest 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | all 19 | runtime; build; native; contentfiles; analyzers; buildtransitive 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/CF.Customer.UnitTest/Domain/Services/PasswordHasherTest.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Domain.Services; 2 | using Xunit; 3 | 4 | namespace CF.Customer.UnitTest.Domain.Services; 5 | 6 | public class PasswordHasherTest 7 | { 8 | [Fact] 9 | public void HashOkTest() 10 | { 11 | //Arrange 12 | const string password = "Blah@!1894"; 13 | var service = new PasswordHasherService(); 14 | 15 | //Act 16 | var result = service.Hash(password); 17 | 18 | //Assert 19 | Assert.NotEqual(password, result); 20 | } 21 | 22 | [Fact] 23 | public void VerifyOkTest() 24 | { 25 | //Arrange 26 | const string password = "Blah@!1894"; 27 | var service = new PasswordHasherService(); 28 | 29 | //Act 30 | var hash = service.Hash(password); 31 | var isValid = service.Verify(password, hash); 32 | 33 | //Assert 34 | Assert.True(isValid); 35 | } 36 | 37 | [Fact] 38 | public void VerifyNotOkTest() 39 | { 40 | //Arrange 41 | const string password = "Blah@!1894"; 42 | const string fakePassword = "Blah@!4981"; 43 | var service = new PasswordHasherService(); 44 | 45 | //Act 46 | var hash = service.Hash(password); 47 | var isValid = service.Verify(fakePassword, hash); 48 | 49 | //Assert 50 | Assert.False(isValid); 51 | } 52 | } -------------------------------------------------------------------------------- /src/CF.Api/CF.Api.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net10.0 4 | enable 5 | latest 6 | 4be108ac-b37e-4a34-9d37-b22846d0bdf1 7 | Linux 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | all 17 | runtime; build; native; contentfiles; analyzers 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | Always 30 | 31 | 32 | -------------------------------------------------------------------------------- /src/CF.Customer.Application/Dtos/CustomerRequestDto.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | 3 | namespace CF.Customer.Application.Dtos; 4 | 5 | public record CustomerRequestDto 6 | { 7 | [Required(ErrorMessage = "The Email field is required.")] 8 | [EmailAddress(ErrorMessage = "The Email field is not a valid email address.")] 9 | [MaxLength(100, ErrorMessage = "The Email field must not exceed 100 characters.")] 10 | [Display(Name = "Email")] 11 | public string Email { get; set; } 12 | 13 | [Required(ErrorMessage = "The First Name field is required.")] 14 | [StringLength(100, MinimumLength = 2, ErrorMessage = "The First Name field must be between 2 and 100 characters.")] 15 | [Display(Name = "First Name")] 16 | public string FirstName { get; set; } 17 | 18 | [Required(ErrorMessage = "The Password field is required.")] 19 | [DataType(DataType.Password)] 20 | [Display(Name = "Password")] 21 | [RegularExpression( 22 | "^((?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])|(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[^a-zA-Z0-9])|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9])|(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9])).{8,}$", 23 | ErrorMessage = 24 | "Passwords must be at least 8 characters and contain at least 3 of the following: upper case (A-Z), lower case (a-z), number (0-9), and special character (e.g. !@#$%^&*).")] 25 | public string Password { get; set; } 26 | 27 | [DataType(DataType.Password)] 28 | [Display(Name = "Confirm password")] 29 | [Compare("Password", ErrorMessage = "The passwords do not match.")] 30 | public string ConfirmPassword { get; set; } 31 | 32 | [Required(ErrorMessage = "The Surname field is required.")] 33 | [StringLength(100, MinimumLength = 2, ErrorMessage = "The Surname field must be between 2 and 100 characters.")] 34 | [Display(Name = "Surname")] 35 | public string Surname { get; set; } 36 | } -------------------------------------------------------------------------------- /src/CF.Api/Filters/ExceptionFilter.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Domain.Exceptions; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.AspNetCore.Mvc.Filters; 4 | 5 | namespace CF.Api.Filters; 6 | 7 | public class ExceptionFilter : IExceptionFilter 8 | { 9 | public void OnException(ExceptionContext context) 10 | { 11 | switch (context.Exception) 12 | { 13 | case ValidationException: 14 | HandleValidationException(context); 15 | break; 16 | case EntityNotFoundException: 17 | HandleEntityNotFoundException(context); 18 | break; 19 | default: 20 | HandleException(context); 21 | break; 22 | } 23 | } 24 | 25 | private static void HandleEntityNotFoundException(ExceptionContext context) 26 | { 27 | context.ExceptionHandled = true; 28 | context.Result = new NotFoundResult(); 29 | } 30 | 31 | private static void HandleValidationException(ExceptionContext context) 32 | { 33 | var error = new KeyValuePair("Errors", new Dictionary> 34 | { 35 | { "Validation", [context.Exception.Message] } 36 | } 37 | ); 38 | 39 | var details = new ProblemDetails 40 | { 41 | Extensions = { error }, 42 | Title = "One validation error occurred.", 43 | Status = StatusCodes.Status400BadRequest, 44 | Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.1" 45 | }; 46 | context.ExceptionHandled = true; 47 | context.Result = new BadRequestObjectResult(details); 48 | } 49 | 50 | private static void HandleException(ExceptionContext context) 51 | { 52 | context.ExceptionHandled = true; 53 | context.Result = new StatusCodeResult(StatusCodes.Status500InternalServerError); 54 | } 55 | } -------------------------------------------------------------------------------- /src/CF.Migrations/Migrations/20240108231037_InitialMigration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace CF.Migrations.Migrations 7 | { 8 | /// 9 | public partial class InitialMigration : Migration 10 | { 11 | /// 12 | protected override void Up(MigrationBuilder migrationBuilder) 13 | { 14 | migrationBuilder.CreateTable( 15 | name: "Customer", 16 | columns: table => new 17 | { 18 | Id = table.Column(type: "bigint", nullable: false) 19 | .Annotation("SqlServer:Identity", "1, 1"), 20 | Created = table.Column(type: "datetime2", nullable: false), 21 | Email = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), 22 | FirstName = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), 23 | Password = table.Column(type: "nvarchar(2000)", maxLength: 2000, nullable: false), 24 | Surname = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), 25 | Updated = table.Column(type: "datetime2", nullable: true) 26 | }, 27 | constraints: table => 28 | { 29 | table.PrimaryKey("PK_Customer", x => x.Id); 30 | }); 31 | 32 | migrationBuilder.CreateIndex( 33 | name: "IX_Customer_Email", 34 | table: "Customer", 35 | column: "Email", 36 | unique: true); 37 | } 38 | 39 | /// 40 | protected override void Down(MigrationBuilder migrationBuilder) 41 | { 42 | migrationBuilder.DropTable( 43 | name: "Customer"); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/CF.Customer.Infrastructure/Mappers/CustomerMapper.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Application.Dtos; 2 | using CF.Customer.Application.Mappers; 3 | using CF.Customer.Domain.Entities; 4 | using CF.Customer.Domain.Models; 5 | 6 | namespace CF.Customer.Infrastructure.Mappers; 7 | 8 | public class CustomerMapper : ICustomerMapper 9 | { 10 | public Domain.Entities.Customer MapToCustomer(CustomerRequestDto dto) 11 | { 12 | return new Domain.Entities.Customer 13 | { 14 | Email = dto.Email, 15 | FirstName = dto.FirstName, 16 | Password = dto.Password, 17 | Surname = dto.Surname 18 | }; 19 | } 20 | 21 | public CustomerResponseDto MapToCustomerResponseDto(Domain.Entities.Customer customer) 22 | { 23 | return new CustomerResponseDto 24 | { 25 | Id = customer.Id, 26 | Email = customer.Email, 27 | FirstName = customer.FirstName, 28 | Surname = customer.Surname, 29 | FullName = customer.GetFullName() 30 | }; 31 | } 32 | 33 | public CustomerFilter MapToCustomerFilter(CustomerFilterDto dto) 34 | { 35 | return new CustomerFilter 36 | { 37 | Id = dto.Id, 38 | Email = dto.Email, 39 | FirstName = dto.FirstName, 40 | Surname = dto.Surname, 41 | CurrentPage = dto.CurrentPage, 42 | PageSize = dto.PageSize, 43 | OrderBy = dto.OrderBy, 44 | SortBy = dto.SortBy 45 | }; 46 | } 47 | 48 | public PaginationDto MapToPaginationDto(Pagination pagination) 49 | { 50 | return new PaginationDto 51 | { 52 | CurrentPage = pagination.CurrentPage, 53 | Count = pagination.Count, 54 | PageSize = pagination.PageSize, 55 | TotalPages = pagination.TotalPages, 56 | Result = pagination.Result.Select(MapToCustomerResponseDto).ToList() 57 | }; 58 | } 59 | } -------------------------------------------------------------------------------- /src/CF.Customer.Application/Facades/CustomerFacade.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Application.Dtos; 2 | using CF.Customer.Application.Facades.Interfaces; 3 | using CF.Customer.Application.Mappers; 4 | using CF.Customer.Domain.Services.Interfaces; 5 | 6 | namespace CF.Customer.Application.Facades; 7 | 8 | public class CustomerFacade(ICustomerService customerService, ICustomerMapper mapper) : ICustomerFacade 9 | { 10 | public async Task> GetListByFilterAsync(CustomerFilterDto filterDto, 11 | CancellationToken cancellationToken) 12 | { 13 | var filter = mapper.MapToCustomerFilter(filterDto); 14 | 15 | var result = await customerService.GetListByFilterAsync(filter, cancellationToken); 16 | 17 | var paginationDto = mapper.MapToPaginationDto(result); 18 | 19 | return paginationDto; 20 | } 21 | 22 | public async Task GetByFilterAsync(CustomerFilterDto filterDto, 23 | CancellationToken cancellationToken) 24 | { 25 | var filter = mapper.MapToCustomerFilter(filterDto); 26 | 27 | var result = await customerService.GetByFilterAsync(filter, cancellationToken); 28 | 29 | var resultDto = mapper.MapToCustomerResponseDto(result); 30 | 31 | return resultDto; 32 | } 33 | 34 | public async Task UpdateAsync(long id, CustomerRequestDto customerRequestDto, CancellationToken cancellationToken) 35 | { 36 | var customer = mapper.MapToCustomer(customerRequestDto); 37 | 38 | await customerService.UpdateAsync(id, customer, cancellationToken); 39 | } 40 | 41 | public async Task CreateAsync(CustomerRequestDto customerRequestDto, CancellationToken cancellationToken) 42 | { 43 | var customer = mapper.MapToCustomer(customerRequestDto); 44 | 45 | var id = await customerService.CreateAsync(customer, cancellationToken); 46 | 47 | return id; 48 | } 49 | 50 | public async Task DeleteAsync(long id, CancellationToken cancellationToken) 51 | { 52 | await customerService.DeleteAsync(id, cancellationToken); 53 | } 54 | } -------------------------------------------------------------------------------- /src/CF.Customer.Infrastructure/Repositories/RepositoryBase.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Domain.Repositories; 2 | using CF.Customer.Infrastructure.DbContext; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace CF.Customer.Infrastructure.Repositories; 6 | 7 | public class RepositoryBase : IRepositoryBase 8 | where TEntity : class 9 | { 10 | protected readonly CustomerContext DbContext; 11 | protected readonly DbSet DbSet; 12 | 13 | public RepositoryBase(CustomerContext context) 14 | { 15 | DbContext = context; 16 | DbSet = DbContext.Set(); 17 | } 18 | 19 | public void Add(TEntity entity) 20 | { 21 | DbSet.Add(entity); 22 | } 23 | 24 | /// 25 | /// This method is async only to allow special value generators, such as the one used by 26 | /// 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database 27 | /// asynchronously. For all other cases the non async method should be used. 28 | /// https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbset-1?view=efcore-3.1#Microsoft_EntityFrameworkCore_DbSet_1_AddAsync__0_System_Threading_CancellationToken_ 29 | /// 30 | public virtual async Task AddAsync(TEntity entity, CancellationToken cancellationToken) 31 | { 32 | await DbSet.AddAsync(entity, cancellationToken); 33 | } 34 | 35 | public virtual async Task GetByIdAsync(long id, CancellationToken cancellationToken) 36 | { 37 | return await DbSet.FindAsync([id, cancellationToken], cancellationToken); 38 | } 39 | 40 | public virtual async Task> GetAllAsync(CancellationToken cancellationToken) 41 | { 42 | return await DbSet.ToListAsync(cancellationToken); 43 | } 44 | 45 | public virtual void Update(TEntity entity) 46 | { 47 | DbSet.Update(entity); 48 | } 49 | 50 | public virtual void Remove(TEntity entity) 51 | { 52 | DbSet.Remove(entity); 53 | } 54 | 55 | public async Task SaveChangesAsync(CancellationToken cancellationToken) 56 | { 57 | return await DbContext.SaveChangesAsync(cancellationToken); 58 | } 59 | 60 | public void Dispose() 61 | { 62 | DbContext.Dispose(); 63 | GC.SuppressFinalize(this); 64 | } 65 | 66 | public virtual async Task AddRangeAsync(IList entities) 67 | { 68 | await DbSet.AddRangeAsync(entities); 69 | } 70 | } -------------------------------------------------------------------------------- /src/CF.Migrations/Migrations/CustomerContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using CF.Customer.Infrastructure.DbContext; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | 9 | #nullable disable 10 | 11 | namespace CF.Migrations.Migrations 12 | { 13 | [DbContext(typeof(CustomerContext))] 14 | partial class CustomerContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "8.0.0") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 22 | 23 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 24 | 25 | modelBuilder.Entity("CF.Customer.Domain.Entities.Customer", b => 26 | { 27 | b.Property("Id") 28 | .ValueGeneratedOnAdd() 29 | .HasColumnType("bigint"); 30 | 31 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 32 | 33 | b.Property("Created") 34 | .HasColumnType("datetime2"); 35 | 36 | b.Property("Email") 37 | .IsRequired() 38 | .HasMaxLength(100) 39 | .HasColumnType("nvarchar(100)"); 40 | 41 | b.Property("FirstName") 42 | .IsRequired() 43 | .HasMaxLength(100) 44 | .HasColumnType("nvarchar(100)"); 45 | 46 | b.Property("Password") 47 | .IsRequired() 48 | .HasMaxLength(2000) 49 | .HasColumnType("nvarchar(2000)"); 50 | 51 | b.Property("Surname") 52 | .IsRequired() 53 | .HasMaxLength(100) 54 | .HasColumnType("nvarchar(100)"); 55 | 56 | b.Property("Updated") 57 | .HasColumnType("datetime2"); 58 | 59 | b.HasKey("Id"); 60 | 61 | b.HasIndex("Email") 62 | .IsUnique(); 63 | 64 | b.ToTable("Customer", (string)null); 65 | }); 66 | #pragma warning restore 612, 618 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/CF.IntegrationTest/RateLimitingIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Threading.Tasks; 3 | using CF.IntegrationTest.Factories; 4 | using Xunit; 5 | 6 | namespace CF.IntegrationTest; 7 | 8 | public class RateLimitingIntegrationTest(CustomWebApplicationFactory factory) 9 | : IClassFixture 10 | { 11 | [Fact] 12 | public async Task RateLimiting_ExceedsLimit_Returns429() 13 | { 14 | // Arrange 15 | var client = factory.CreateClient(); 16 | const int requestCount = 62; 17 | var successCount = 0; 18 | var rateLimitCount = 0; 19 | 20 | // Act 21 | for (var i = 0; i < requestCount; i++) 22 | { 23 | var response = await client.GetAsync("/health/live"); 24 | 25 | switch (response.StatusCode) 26 | { 27 | case HttpStatusCode.OK: 28 | successCount++; 29 | break; 30 | case HttpStatusCode.TooManyRequests: 31 | { 32 | rateLimitCount++; 33 | 34 | var content = await response.Content.ReadAsStringAsync(); 35 | Assert.Contains("Rate limit exceeded", content); 36 | Assert.Contains("retryAfter", content); 37 | break; 38 | } 39 | } 40 | } 41 | 42 | // Assert 43 | Assert.True(rateLimitCount > 0, "Rate limiting should have triggered at least once"); 44 | Assert.True(successCount > 0, "Some requests should have succeeded"); 45 | } 46 | 47 | [Fact] 48 | public async Task RateLimiting_WithinLimit_AllSucceed() 49 | { 50 | // Arrange 51 | var client = factory.CreateClient(); 52 | const int requestCount = 10; 53 | 54 | // Act & Assert 55 | for (var i = 0; i < requestCount; i++) 56 | { 57 | var response = await client.GetAsync("/health/live"); 58 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 59 | } 60 | } 61 | 62 | [Fact] 63 | public async Task RateLimiting_DifferentEndpoints_SharesLimit() 64 | { 65 | // Arrange 66 | var client = factory.CreateClient(); 67 | 68 | // Act 69 | var response1 = await client.GetAsync("/health/live"); 70 | var response2 = await client.GetAsync("/health/ready"); 71 | var response3 = await client.GetAsync("/health"); 72 | 73 | // Assert 74 | Assert.Equal(HttpStatusCode.OK, response1.StatusCode); 75 | Assert.Equal(HttpStatusCode.OK, response2.StatusCode); 76 | Assert.Equal(HttpStatusCode.OK, response3.StatusCode); 77 | } 78 | } -------------------------------------------------------------------------------- /src/CF.IntegrationTest/ApiVersioningIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | using System.Net.Http.Headers; 5 | using System.Threading.Tasks; 6 | using CF.Customer.Application.Dtos; 7 | using CF.IntegrationTest.Factories; 8 | using Newtonsoft.Json; 9 | using Xunit; 10 | 11 | namespace CF.IntegrationTest; 12 | 13 | public class ApiVersioningIntegrationTest(CustomWebApplicationFactory factory) 14 | : IClassFixture 15 | { 16 | [Fact] 17 | public async Task ApiVersioning_V1Endpoint_ReturnsSuccess() 18 | { 19 | // Arrange 20 | var client = factory.CreateClient(); 21 | 22 | // Act 23 | var response = await client.GetAsync("/api/v1/customer?pageSize=10"); 24 | 25 | // Assert 26 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 27 | } 28 | 29 | [Fact] 30 | public async Task ApiVersioning_ResponseHeaders_ContainVersionInfo() 31 | { 32 | // Arrange 33 | var client = factory.CreateClient(); 34 | 35 | // Act 36 | var response = await client.GetAsync("/api/v1/customer?pageSize=10"); 37 | 38 | // Assert 39 | Assert.True(response.Headers.Contains("api-supported-versions"), 40 | "Response should contain api-supported-versions header"); 41 | } 42 | 43 | [Fact] 44 | public async Task ApiVersioning_PostReturnsCorrectLocation() 45 | { 46 | // Arrange 47 | var client = factory.CreateClient(); 48 | var dto = new CustomerRequestDto 49 | { 50 | FirstName = "Test", 51 | Surname = "Versioning", 52 | Email = $"versioning_{DateTime.Now:yyyyMMddHHmmss}@test.com", 53 | Password = "Test@1234", 54 | ConfirmPassword = "Test@1234" 55 | }; 56 | 57 | var content = new StringContent(JsonConvert.SerializeObject(dto)); 58 | content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 59 | 60 | // Act 61 | var response = await client.PostAsync("/api/v1/customer", content); 62 | 63 | // Assert 64 | Assert.Equal(HttpStatusCode.Created, response.StatusCode); 65 | Assert.NotNull(response.Headers.Location); 66 | Assert.Contains("/api/v1/customer/", response.Headers.Location?.ToString()); 67 | } 68 | 69 | [Fact] 70 | public async Task ApiVersioning_InvalidVersion_ReturnsNotFound() 71 | { 72 | // Arrange 73 | var client = factory.CreateClient(); 74 | 75 | // Act 76 | var response = await client.GetAsync("/api/v2/customer"); 77 | 78 | // Assert 79 | Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); 80 | } 81 | } -------------------------------------------------------------------------------- /src/CF.Migrations/Migrations/20240108231037_InitialMigration.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using CF.Customer.Infrastructure.DbContext; 4 | using Microsoft.EntityFrameworkCore; 5 | using Microsoft.EntityFrameworkCore.Infrastructure; 6 | using Microsoft.EntityFrameworkCore.Metadata; 7 | using Microsoft.EntityFrameworkCore.Migrations; 8 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 9 | 10 | #nullable disable 11 | 12 | namespace CF.Migrations.Migrations 13 | { 14 | [DbContext(typeof(CustomerContext))] 15 | [Migration("20240108231037_InitialMigration")] 16 | partial class InitialMigration 17 | { 18 | /// 19 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 20 | { 21 | #pragma warning disable 612, 618 22 | modelBuilder 23 | .HasAnnotation("ProductVersion", "8.0.0") 24 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 25 | 26 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); 27 | 28 | modelBuilder.Entity("CF.Customer.Domain.Entities.Customer", b => 29 | { 30 | b.Property("Id") 31 | .ValueGeneratedOnAdd() 32 | .HasColumnType("bigint"); 33 | 34 | SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); 35 | 36 | b.Property("Created") 37 | .HasColumnType("datetime2"); 38 | 39 | b.Property("Email") 40 | .IsRequired() 41 | .HasMaxLength(100) 42 | .HasColumnType("nvarchar(100)"); 43 | 44 | b.Property("FirstName") 45 | .IsRequired() 46 | .HasMaxLength(100) 47 | .HasColumnType("nvarchar(100)"); 48 | 49 | b.Property("Password") 50 | .IsRequired() 51 | .HasMaxLength(2000) 52 | .HasColumnType("nvarchar(2000)"); 53 | 54 | b.Property("Surname") 55 | .IsRequired() 56 | .HasMaxLength(100) 57 | .HasColumnType("nvarchar(100)"); 58 | 59 | b.Property("Updated") 60 | .HasColumnType("datetime2"); 61 | 62 | b.HasKey("Id"); 63 | 64 | b.HasIndex("Email") 65 | .IsUnique(); 66 | 67 | b.ToTable("Customer", (string)null); 68 | }); 69 | #pragma warning restore 612, 618 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/CF.IntegrationTest/Factories/CustomWebApplicationFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using CF.Customer.Infrastructure.DbContext; 6 | using CF.IntegrationTest.Seeds; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.AspNetCore.Mvc.Testing; 9 | using Microsoft.EntityFrameworkCore; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Logging; 12 | 13 | namespace CF.IntegrationTest.Factories; 14 | 15 | public class CustomWebApplicationFactory : WebApplicationFactory 16 | { 17 | private readonly string _connectionString = $"DataSource={Guid.NewGuid()}.db"; 18 | 19 | protected override void ConfigureWebHost(IWebHostBuilder builder) 20 | { 21 | builder.ConfigureServices(services => 22 | { 23 | var registrationsTypeToRemove = new List 24 | { 25 | typeof(DbContextOptions), 26 | typeof(CustomerContext) 27 | }; 28 | 29 | RemoveRegistrations(services, registrationsTypeToRemove); 30 | 31 | var serviceProvider = new ServiceCollection() 32 | .AddEntityFrameworkSqlite() 33 | .BuildServiceProvider(); 34 | 35 | services.AddDbContext(options => 36 | { 37 | options.UseSqlite(_connectionString); 38 | options.UseInternalServiceProvider(serviceProvider); 39 | }); 40 | 41 | var sp = services.BuildServiceProvider(); 42 | using var scope = sp.CreateScope(); 43 | using var dbContext = scope.ServiceProvider.GetRequiredService(); 44 | dbContext.Database.EnsureCreated(); 45 | var logger = scope.ServiceProvider.GetRequiredService>(); 46 | 47 | try 48 | { 49 | Task.FromResult(CustomerSeed.PopulateAsync(dbContext)); 50 | } 51 | catch (Exception ex) 52 | { 53 | logger.LogError(ex, "An error occurred while seeding the database with test data."); 54 | } 55 | }); 56 | 57 | builder.UseEnvironment("IntegrationTest"); 58 | } 59 | 60 | protected static void RemoveRegistration(IServiceCollection services, Type type) 61 | { 62 | var currentRegistration = services.FirstOrDefault(c => c.ServiceType == type); 63 | if (currentRegistration != null) services.Remove(currentRegistration); 64 | } 65 | 66 | protected static void RemoveRegistrations(IServiceCollection services, IEnumerable types) 67 | { 68 | foreach (var type in types) RemoveRegistration(services, type); 69 | } 70 | } -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # ******** NOTE ******** 12 | 13 | name: "CodeQL" 14 | 15 | on: 16 | push: 17 | branches: [ main ] 18 | pull_request: 19 | # The branches below must be a subset of the branches above 20 | branches: [ main ] 21 | schedule: 22 | - cron: '25 18 * * 4' 23 | 24 | jobs: 25 | analyze: 26 | name: Analyze 27 | runs-on: ubuntu-latest 28 | 29 | strategy: 30 | fail-fast: false 31 | matrix: 32 | language: [ 'csharp' ] 33 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] 34 | # Learn more: 35 | # https://docs.github.com/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed 36 | 37 | steps: 38 | - uses: actions/checkout@v4 39 | - uses: actions/setup-dotnet@v4 40 | with: 41 | dotnet-version: 10.0.x 42 | - name: Install dependencies 43 | run: dotnet restore 44 | - name: Build 45 | run: dotnet build --configuration Release --no-restore 46 | - name: Test 47 | run: dotnet test --no-restore --verbosity normal 48 | 49 | 50 | # Initializes the CodeQL tools for scanning. 51 | - name: Initialize CodeQL 52 | uses: github/codeql-action/init@v4 53 | with: 54 | languages: ${{ matrix.language }} 55 | # If you wish to specify custom queries, you can do so here or in a config file. 56 | # By default, queries listed here will override any specified in a config file. 57 | # Prefix the list here with "+" to use these queries and those in the config file. 58 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 59 | 60 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 61 | # If this step fails, then you should remove it and run the build manually (see below) 62 | - name: Autobuild 63 | uses: github/codeql-action/autobuild@v4 64 | 65 | # ℹ️ Command-line programs to run using the OS shell. 66 | # 📚 https://git.io/JvXDl 67 | 68 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 69 | # and modify them (or add more) to build your code if your project 70 | # uses a compiled language 71 | 72 | #- run: | 73 | # make bootstrap 74 | # make release 75 | 76 | - name: Perform CodeQL Analysis 77 | uses: github/codeql-action/analyze@v4 78 | -------------------------------------------------------------------------------- /src/CF.Api/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "ConnectionStrings": { 3 | "DbConnection": "Data Source=db;Initial Catalog=CF;User ID=sa;Password=CF@!1234FC6549;Trusted_Connection=false;TrustServerCertificate=True;" 4 | }, 5 | "RateLimiting": { 6 | "PermitLimit": 60, 7 | "WindowSeconds": 60 8 | }, 9 | "Logging": { 10 | "LogLevel": { 11 | "Default": "Trace", 12 | "System": "Information", 13 | "Microsoft": "Information" 14 | } 15 | }, 16 | "NLog": { 17 | "autoReload": true, 18 | "throwConfigExceptions": true, 19 | "default-wrapper": { 20 | "type": "AsyncWrapper", 21 | "overflowAction": "Block" 22 | }, 23 | "targets": { 24 | "file": { 25 | "type": "File", 26 | "fileName": "${basedir}/CfApi.log", 27 | "archiveFileName": "${basedir}/archive-files/${shortdate}.{####}-CfApi.log", 28 | "archiveEvery": "Day", 29 | "archiveAboveSize": "67108864", 30 | "archiveNumbering": "DateAndSequence", 31 | "archiveOldFileOnStartup": "true", 32 | "maxArchiveFiles": "10", 33 | "keepFileOpen": "false", 34 | "deleteOldFileOnStartup": "false", 35 | "createDirs": "true", 36 | "layout": { 37 | "type": "JsonLayout", 38 | "includeAllProperties": "true", 39 | "maxRecursionLimit": "10", 40 | "Attributes": [ 41 | { 42 | "name": "time", 43 | "layout": "${longDate}" 44 | }, 45 | { 46 | "name": "level", 47 | "layout": "${level:upperCase=true}" 48 | }, 49 | { 50 | "name": "source", 51 | "layout": "${callsite}" 52 | }, 53 | { 54 | "name": "message", 55 | "layout": "${message}" 56 | }, 57 | { 58 | "name": "exception", 59 | "layout": "${exception:format=toString}" 60 | } 61 | ] 62 | } 63 | }, 64 | "console": { 65 | "type": "LimitingWrapper", 66 | "interval": "00:00:01", 67 | "messageLimit": 100, 68 | "target": { 69 | "type": "ColoredConsole", 70 | "layout": 71 | "${longDate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|${callsite}", 72 | "rowHighlightingRules": [ 73 | { 74 | "condition": "level == LogLevel.Error", 75 | "foregroundColor": "Red" 76 | }, 77 | { 78 | "condition": "level == LogLevel.Fatal", 79 | "foregroundColor": "Red", 80 | "backgroundColor": "White" 81 | } 82 | ] 83 | } 84 | } 85 | }, 86 | "rules": [ 87 | { 88 | "logger": "*", 89 | "minLevel": "Trace", 90 | "writeTo": "file, console" 91 | } 92 | ] 93 | } 94 | } -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Entities/CustomerExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Text.RegularExpressions; 2 | using CF.Customer.Domain.Exceptions; 3 | 4 | namespace CF.Customer.Domain.Entities; 5 | 6 | public static partial class CustomerExtensions 7 | { 8 | [GeneratedRegex( 9 | @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", 10 | RegexOptions.IgnoreCase, "en-US")] 11 | private static partial Regex EmailValidatorRegex(); 12 | 13 | extension(Customer customer) 14 | { 15 | public string GetFullName() 16 | { 17 | return $"{customer.FirstName} {customer.Surname}"; 18 | } 19 | 20 | public void SetCreatedDate() 21 | { 22 | customer.Created = DateTime.UtcNow; 23 | } 24 | 25 | public void SetUpdatedDate() 26 | { 27 | customer.Updated = DateTime.UtcNow; 28 | } 29 | 30 | public void ValidatePassword() 31 | { 32 | if (string.IsNullOrEmpty(customer.Password)) 33 | throw new ValidationException("The Password is required."); 34 | 35 | const string regex = 36 | @"^((?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])|(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[^a-zA-Z0-9])|(?=.*?[A-Z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9])|(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^a-zA-Z0-9])).{8,}$"; 37 | 38 | if (!Regex.IsMatch(customer.Password, regex)) 39 | throw new ValidationException( 40 | "Password must be at least 8 characters and contain at 3 of the following: upper case (A-Z), lower case (a-z), number (0-9) and special character (e.g. !@#$%^&*)."); 41 | } 42 | 43 | public void ValidateEmail() 44 | { 45 | if (string.IsNullOrEmpty(customer.Email)) 46 | throw new ValidationException("The Email is required."); 47 | 48 | if (!EmailValidatorRegex().IsMatch(customer.Email)) 49 | throw new ValidationException("The Email is not a valid e-mail address."); 50 | } 51 | 52 | public void ValidateSurname() 53 | { 54 | if (string.IsNullOrEmpty(customer.Surname)) 55 | throw new ValidationException("The Surname is required."); 56 | 57 | if (customer.Surname.Length is < 2 or > 100) 58 | throw new ValidationException( 59 | "The Surname must be a string with a minimum length of 2 and a maximum length of 100."); 60 | } 61 | 62 | public void ValidateFirstName() 63 | { 64 | if (string.IsNullOrEmpty(customer.FirstName)) 65 | throw new ValidationException("The First Name is required."); 66 | 67 | if (customer.FirstName.Length is < 2 or > 100) 68 | throw new ValidationException( 69 | "The First Name must be a string with a minimum length of 2 and a maximum length of 100."); 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /src/CF.Customer.Infrastructure/Repositories/CustomerRepository.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Domain.Models; 2 | using CF.Customer.Domain.Repositories; 3 | using CF.Customer.Infrastructure.DbContext; 4 | using Microsoft.EntityFrameworkCore; 5 | 6 | namespace CF.Customer.Infrastructure.Repositories; 7 | 8 | public class CustomerRepository(CustomerContext context) 9 | : RepositoryBase(context), ICustomerRepository 10 | { 11 | public async Task CountByFilterAsync(CustomerFilter filter, CancellationToken cancellationToken) 12 | { 13 | var query = DbContext.Customers.AsQueryable(); 14 | 15 | query = ApplyFilter(filter, query); 16 | 17 | return await query.CountAsync(cancellationToken); 18 | } 19 | 20 | public async Task GetByFilterAsync(CustomerFilter filter, 21 | CancellationToken cancellationToken) 22 | { 23 | var query = DbContext.Customers.AsQueryable(); 24 | 25 | query = ApplyFilter(filter, query); 26 | 27 | return await query.FirstOrDefaultAsync(cancellationToken); 28 | } 29 | 30 | public async Task> GetListByFilterAsync(CustomerFilter filter, 31 | CancellationToken cancellationToken) 32 | { 33 | var query = DbContext.Customers.AsQueryable(); 34 | 35 | query = ApplyFilter(filter, query); 36 | 37 | query = ApplySorting(filter, query); 38 | 39 | if (filter.CurrentPage > 0) 40 | query = query.Skip((filter.CurrentPage - 1) * filter.PageSize).Take(filter.PageSize); 41 | 42 | return await query.ToListAsync(cancellationToken); 43 | } 44 | 45 | private static IQueryable ApplySorting(CustomerFilter filter, 46 | IQueryable query) 47 | { 48 | query = filter?.OrderBy.ToLower() switch 49 | { 50 | "firstname" => filter.SortBy.Equals("asc", StringComparison.CurrentCultureIgnoreCase) 51 | ? query.OrderBy(x => x.FirstName) 52 | : query.OrderByDescending(x => x.FirstName), 53 | "surname" => filter.SortBy.Equals("asc", StringComparison.CurrentCultureIgnoreCase) 54 | ? query.OrderBy(x => x.Surname) 55 | : query.OrderByDescending(x => x.Surname), 56 | "email" => filter.SortBy.Equals("asc", StringComparison.CurrentCultureIgnoreCase) 57 | ? query.OrderBy(x => x.Email) 58 | : query.OrderByDescending(x => x.Email), 59 | _ => query 60 | }; 61 | 62 | return query; 63 | } 64 | 65 | private static IQueryable ApplyFilter(CustomerFilter filter, 66 | IQueryable query) 67 | { 68 | if (filter.Id > 0) 69 | query = query.Where(x => x.Id == filter.Id); 70 | 71 | if (!string.IsNullOrWhiteSpace(filter.FirstName)) 72 | query = query.Where(x => EF.Functions.Like(x.FirstName, $"%{filter.FirstName}%")); 73 | 74 | if (!string.IsNullOrWhiteSpace(filter.Surname)) 75 | query = query.Where(x => EF.Functions.Like(x.Surname, $"%{filter.Surname}%")); 76 | 77 | if (!string.IsNullOrWhiteSpace(filter.Email)) 78 | query = query.Where(x => x.Email == filter.Email); 79 | 80 | return query; 81 | } 82 | } -------------------------------------------------------------------------------- /src/CF.Api/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | }, 8 | "NLog": { 9 | "IncludeScopes": true 10 | } 11 | }, 12 | "NLog": { 13 | "autoReload": true, 14 | "throwConfigExceptions": true, 15 | "default-wrapper": { 16 | "type": "AsyncWrapper", 17 | "overflowAction": "Block" 18 | }, 19 | "targets": { 20 | "file": { 21 | "type": "File", 22 | "fileName": "${basedir}/CfApi.log", 23 | "archiveFileName": "${basedir}/archive-files/${shortdate}.{####}-CfApi.log", 24 | "archiveEvery": "Day", 25 | "archiveAboveSize": "67108864", 26 | "archiveNumbering": "DateAndSequence", 27 | "archiveOldFileOnStartup": "true", 28 | "maxArchiveFiles": "10", 29 | "keepFileOpen": "false", 30 | "deleteOldFileOnStartup": "false", 31 | "createDirs": "true", 32 | "layout": { 33 | "type": "JsonLayout", 34 | "includeAllProperties": "true", 35 | "maxRecursionLimit": "10", 36 | "Attributes": [ 37 | { 38 | "name": "time", 39 | "layout": "${longDate}" 40 | }, 41 | { 42 | "name": "level", 43 | "layout": "${level:upperCase=true}" 44 | }, 45 | { 46 | "name": "correlationId", 47 | "layout": "${event-properties:item=correlationId}" 48 | }, 49 | { 50 | "name": "action", 51 | "layout": "${event-properties:item=action}" 52 | }, 53 | { 54 | "name": "source", 55 | "layout": "${callsite}" 56 | }, 57 | { 58 | "name": "parameters", 59 | "layout": "${event-properties:item=parameters}", 60 | "encode": false 61 | }, 62 | { 63 | "name": "message", 64 | "layout": "${message}" 65 | }, 66 | { 67 | "name": "exception", 68 | "layout": "${exception:format=toString}" 69 | }, 70 | { 71 | "name": "properties", 72 | "layout": "${longDate} ${logger} ${message}" 73 | } 74 | ] 75 | } 76 | }, 77 | "console": { 78 | "type": "LimitingWrapper", 79 | "interval": "00:00:01", 80 | "messageLimit": 100, 81 | "target": { 82 | "type": "ColoredConsole", 83 | "layout": 84 | "${longDate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|${callsite}", 85 | "rowHighlightingRules": [ 86 | { 87 | "condition": "level == LogLevel.Error", 88 | "foregroundColor": "Red" 89 | }, 90 | { 91 | "condition": "level == LogLevel.Fatal", 92 | "foregroundColor": "Red", 93 | "backgroundColor": "White" 94 | } 95 | ] 96 | } 97 | } 98 | }, 99 | "rules": [ 100 | { 101 | "logger": "*", 102 | "minLevel": "Trace", 103 | "writeTo": "file, console" 104 | } 105 | ] 106 | } 107 | } -------------------------------------------------------------------------------- /src/CF.IntegrationTest/HealthCheckIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Text.Json; 3 | using System.Threading.Tasks; 4 | using CF.IntegrationTest.Factories; 5 | using Xunit; 6 | 7 | namespace CF.IntegrationTest; 8 | 9 | public class HealthCheckIntegrationTest(CustomWebApplicationFactory factory) 10 | : IClassFixture 11 | { 12 | private readonly CustomWebApplicationFactory _factory = factory; 13 | 14 | [Fact] 15 | public async Task HealthCheck_Full_ReturnsHealthyStatus() 16 | { 17 | // Arrange 18 | var client = _factory.CreateClient(); 19 | 20 | // Act 21 | var response = await client.GetAsync("/health"); 22 | 23 | // Assert 24 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 25 | Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); 26 | 27 | var content = await response.Content.ReadAsStringAsync(); 28 | var healthReport = JsonSerializer.Deserialize(content); 29 | 30 | Assert.Equal("Healthy", healthReport.GetProperty("status").GetString()); 31 | // In test environment, we only have basic health checks (no database) 32 | Assert.True(healthReport.GetProperty("checks").GetArrayLength() >= 0); 33 | Assert.True(healthReport.GetProperty("totalDuration").GetDouble() >= 0); 34 | } 35 | 36 | [Fact] 37 | public async Task HealthCheck_Ready_ChecksDatabaseConnectivity() 38 | { 39 | // Arrange 40 | var client = _factory.CreateClient(); 41 | 42 | // Act 43 | var response = await client.GetAsync("/health/ready"); 44 | 45 | // Assert - In test environment, this endpoint exists but may not have database checks 46 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 47 | } 48 | 49 | [Fact] 50 | public async Task HealthCheck_Live_ReturnsHealthy() 51 | { 52 | // Arrange 53 | var client = _factory.CreateClient(); 54 | 55 | // Act 56 | var response = await client.GetAsync("/health/live"); 57 | 58 | // Assert 59 | Assert.Equal(HttpStatusCode.OK, response.StatusCode); 60 | } 61 | 62 | [Fact(Skip = "Database checks are disabled in test environment")] 63 | public async Task HealthCheck_Full_ContainsDatabaseCheck() 64 | { 65 | // Arrange 66 | var client = _factory.CreateClient(); 67 | 68 | // Act 69 | var response = await client.GetAsync("/health"); 70 | var content = await response.Content.ReadAsStringAsync(); 71 | var healthReport = JsonSerializer.Deserialize(content); 72 | 73 | // Assert 74 | var checks = healthReport.GetProperty("checks"); 75 | var hasDatabaseCheck = false; 76 | var hasSelfCheck = false; 77 | 78 | foreach (var check in checks.EnumerateArray()) 79 | { 80 | var name = check.GetProperty("name").GetString(); 81 | if (name == "database") hasDatabaseCheck = true; 82 | if (name == "self") hasSelfCheck = true; 83 | } 84 | 85 | Assert.True(hasDatabaseCheck, "Health check should include database check"); 86 | Assert.True(hasSelfCheck, "Health check should include self check"); 87 | } 88 | 89 | [Fact] 90 | public async Task HealthCheck_Full_IncludesDurationMetrics() 91 | { 92 | // Arrange 93 | var client = _factory.CreateClient(); 94 | 95 | // Act 96 | var response = await client.GetAsync("/health"); 97 | var content = await response.Content.ReadAsStringAsync(); 98 | var healthReport = JsonSerializer.Deserialize(content); 99 | 100 | // Assert 101 | var checks = healthReport.GetProperty("checks"); 102 | foreach (var check in checks.EnumerateArray()) 103 | { 104 | Assert.True(check.TryGetProperty("duration", out var duration)); 105 | Assert.True(duration.GetDouble() >= 0, "Duration should be non-negative"); 106 | } 107 | 108 | Assert.True(healthReport.GetProperty("totalDuration").GetDouble() >= 0); 109 | } 110 | } -------------------------------------------------------------------------------- /src/CF.Customer.Domain/Services/CustomerService.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Domain.Entities; 2 | using CF.Customer.Domain.Exceptions; 3 | using CF.Customer.Domain.Models; 4 | using CF.Customer.Domain.Repositories; 5 | using CF.Customer.Domain.Services.Interfaces; 6 | 7 | namespace CF.Customer.Domain.Services; 8 | 9 | public class CustomerService(ICustomerRepository customerRepository, IPasswordHasherService passwordHasherService) 10 | : ICustomerService 11 | { 12 | public async Task> GetListByFilterAsync(CustomerFilter filter, 13 | CancellationToken cancellationToken) 14 | { 15 | if (filter is null) 16 | throw new ValidationException("Filter is null."); 17 | 18 | if (filter.PageSize > 100) 19 | throw new ValidationException("Maximum allowed page size is 100."); 20 | 21 | if (filter.CurrentPage <= 0) filter.PageSize = 1; 22 | 23 | var total = await customerRepository.CountByFilterAsync(filter, cancellationToken); 24 | 25 | if (total == 0) return new Pagination(); 26 | 27 | var paginateResult = await customerRepository.GetListByFilterAsync(filter, cancellationToken); 28 | 29 | var result = new Pagination 30 | { 31 | Count = total, 32 | CurrentPage = filter.CurrentPage, 33 | PageSize = filter.PageSize, 34 | Result = [.. paginateResult] 35 | }; 36 | 37 | return result; 38 | } 39 | 40 | public async Task GetByFilterAsync(CustomerFilter filter, CancellationToken cancellationToken) 41 | { 42 | if (filter is null) 43 | throw new ValidationException("Filter is null."); 44 | 45 | return await customerRepository.GetByFilterAsync(filter, cancellationToken); 46 | } 47 | 48 | public async Task UpdateAsync(long id, Entities.Customer customer, CancellationToken cancellationToken) 49 | { 50 | if (id <= 0) throw new ValidationException("Id is invalid."); 51 | 52 | if (customer is null) 53 | throw new ValidationException("Customer is null."); 54 | 55 | var entity = await customerRepository.GetByIdAsync(id, cancellationToken) ?? 56 | throw new EntityNotFoundException(id); 57 | 58 | Validate(customer); 59 | 60 | if (entity.Email != customer.Email && !await IsAvailableEmailAsync(customer.Email, cancellationToken)) 61 | throw new ValidationException("Email is not available."); 62 | 63 | entity.Email = customer.Email; 64 | entity.FirstName = customer.FirstName; 65 | entity.Surname = customer.Surname; 66 | 67 | if (!passwordHasherService.Verify(customer.Password, entity.Password)) 68 | entity.Password = passwordHasherService.Hash(customer.Password); 69 | 70 | entity.SetUpdatedDate(); 71 | await customerRepository.SaveChangesAsync(cancellationToken); 72 | } 73 | 74 | public async Task CreateAsync(Entities.Customer customer, CancellationToken cancellationToken) 75 | { 76 | if (customer is null) 77 | throw new ValidationException("Customer is null."); 78 | 79 | Validate(customer); 80 | 81 | var isAvailableEmail = await IsAvailableEmailAsync(customer.Email, cancellationToken); 82 | if (!isAvailableEmail) throw new ValidationException("Email is not available."); 83 | 84 | customer.Password = passwordHasherService.Hash(customer.Password); 85 | customer.SetCreatedDate(); 86 | customerRepository.Add(customer); 87 | await customerRepository.SaveChangesAsync(cancellationToken); 88 | 89 | return customer.Id; 90 | } 91 | 92 | public async Task DeleteAsync(long id, CancellationToken cancellationToken) 93 | { 94 | if (id <= 0) throw new ValidationException("Id is invalid."); 95 | 96 | var entity = await customerRepository.GetByIdAsync(id, cancellationToken) ?? 97 | throw new EntityNotFoundException(id); 98 | customerRepository.Remove(entity); 99 | await customerRepository.SaveChangesAsync(cancellationToken); 100 | } 101 | 102 | public async Task IsAvailableEmailAsync(string email, CancellationToken cancellationToken) 103 | { 104 | var filter = new CustomerFilter { Email = email }; 105 | var existingEmail = await customerRepository.GetByFilterAsync(filter, cancellationToken); 106 | return existingEmail is null; 107 | } 108 | 109 | private static void Validate(Entities.Customer customer) 110 | { 111 | customer.ValidateFirstName(); 112 | 113 | customer.ValidateSurname(); 114 | 115 | customer.ValidateEmail(); 116 | 117 | customer.ValidatePassword(); 118 | } 119 | } -------------------------------------------------------------------------------- /src/CF.Customer.UnitTest/Infrastructure/Mappers/CustomerMapperTest.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Application.Dtos; 2 | using CF.Customer.Application.Mappers; 3 | using CF.Customer.Domain.Entities; 4 | using CF.Customer.Domain.Models; 5 | using CF.Customer.Infrastructure.Mappers; 6 | using Xunit; 7 | 8 | namespace CF.Customer.UnitTest.Infrastructure.Mappers; 9 | 10 | public class CustomerMapperTest 11 | { 12 | private readonly ICustomerMapper _mapper = new CustomerMapper(); 13 | 14 | [Fact] 15 | public void CustomerRequestDtoToCustomer() 16 | { 17 | //Arrange 18 | var customerRequestDto = new CustomerRequestDto 19 | { 20 | Surname = "Dickinson", 21 | FirstName = "Bruce", 22 | Password = "Blah@1234!", 23 | Email = "maiden@metal.com" 24 | }; 25 | 26 | //Act 27 | var customer = _mapper.MapToCustomer(customerRequestDto); 28 | 29 | //Assert 30 | Assert.Equal(customerRequestDto.FirstName, customer.FirstName); 31 | Assert.Equal(customerRequestDto.Surname, customer.Surname); 32 | Assert.Equal(customerRequestDto.Password, customer.Password); 33 | Assert.Equal(customerRequestDto.Email, customer.Email); 34 | } 35 | 36 | [Fact] 37 | public void CustomerToCustomerResponseDto() 38 | { 39 | //Arrange 40 | var customer = new Customer.Domain.Entities.Customer 41 | { 42 | Surname = "Dickinson", 43 | FirstName = "Bruce", 44 | Email = "maiden@metal.com", 45 | Created = DateTime.Now, 46 | Updated = DateTime.Now, 47 | Id = 1 48 | }; 49 | 50 | //Act 51 | var customerResponseDto = _mapper.MapToCustomerResponseDto(customer); 52 | 53 | //Assert 54 | Assert.Equal(customer.FirstName, customerResponseDto.FirstName); 55 | Assert.Equal(customer.Surname, customerResponseDto.Surname); 56 | Assert.Equal(customer.Email, customerResponseDto.Email); 57 | Assert.Equal(customer.Id, customerResponseDto.Id); 58 | Assert.Equal(customer.GetFullName(), customerResponseDto.FullName); 59 | } 60 | 61 | [Fact] 62 | public void CustomerPaginationToCustomerResponseDtoPagination() 63 | { 64 | //Arrange 65 | var customerList = new List 66 | { 67 | new() 68 | { 69 | Surname = "Dickinson", 70 | FirstName = "Bruce", 71 | Email = "maiden@metal.com", 72 | Created = DateTime.Now, 73 | Updated = DateTime.Now, 74 | Id = 1 75 | } 76 | }; 77 | 78 | var customerPagination = new Pagination 79 | { 80 | Count = 1, 81 | CurrentPage = 1, 82 | PageSize = 1, 83 | Result = customerList 84 | }; 85 | 86 | //Act 87 | var customerResponseDtoPagination = _mapper.MapToPaginationDto(customerPagination); 88 | 89 | //Assert 90 | Assert.Equal(customerList.First().FirstName, customerResponseDtoPagination.Result.First().FirstName); 91 | Assert.Equal(customerList.First().Surname, customerResponseDtoPagination.Result.First().Surname); 92 | Assert.Equal(customerList.First().Email, customerResponseDtoPagination.Result.First().Email); 93 | Assert.Equal(customerList.First().Id, customerResponseDtoPagination.Result.First().Id); 94 | Assert.Equal(customerList.First().GetFullName(), customerResponseDtoPagination.Result.First().FullName); 95 | Assert.Equal(1, customerResponseDtoPagination.TotalPages); 96 | } 97 | 98 | [Fact] 99 | public void CustomerFilterToCustomerFilterDto() 100 | { 101 | //Arrange 102 | var customerFilterDto = new CustomerFilterDto 103 | { 104 | Surname = "Dickinson", 105 | FirstName = "Bruce", 106 | Email = "maiden@metal.com", 107 | Id = 1, 108 | CurrentPage = 1, 109 | PageSize = 1, 110 | OrderBy = "desc", 111 | SortBy = "firstName" 112 | }; 113 | 114 | //Act 115 | var customerFilter = _mapper.MapToCustomerFilter(customerFilterDto); 116 | 117 | //Assert 118 | Assert.Equal(customerFilterDto.FirstName, customerFilter.FirstName); 119 | Assert.Equal(customerFilterDto.Surname, customerFilter.Surname); 120 | Assert.Equal(customerFilterDto.Id, customerFilter.Id); 121 | Assert.Equal(customerFilterDto.Email, customerFilter.Email); 122 | Assert.Equal(customerFilterDto.CurrentPage, customerFilter.CurrentPage); 123 | Assert.Equal(customerFilterDto.OrderBy, customerFilter.OrderBy); 124 | Assert.Equal(customerFilterDto.PageSize, customerFilter.PageSize); 125 | Assert.Equal(customerFilterDto.SortBy, customerFilter.SortBy); 126 | } 127 | } -------------------------------------------------------------------------------- /CF.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31919.166 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CF.Api", "src\CF.Api\CF.Api.csproj", "{AE02CD1D-9F37-495A-B32F-1317B2F42022}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CF.Customer.Application", "src\CF.Customer.Application\CF.Customer.Application.csproj", "{40931CEC-045A-4E2F-8745-A76AD15FA53B}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CF.Customer.Domain", "src\CF.Customer.Domain\CF.Customer.Domain.csproj", "{9F7F03FA-CD8C-436E-976F-AC624064E858}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CF.Customer.Infrastructure", "src\CF.Customer.Infrastructure\CF.Customer.Infrastructure.csproj", "{A981F9D2-ABEE-46C9-953D-1892E1E76BD5}" 13 | EndProject 14 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Customer", "Customer", "{FAD9F9C1-F3EE-4881-8A71-67F4EB69B1AA}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CF.Customer.UnitTest", "src\CF.Customer.UnitTest\CF.Customer.UnitTest.csproj", "{6C787844-6222-4D34-B8ED-813A39E468EA}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CF.IntegrationTest", "src\CF.IntegrationTest\CF.IntegrationTest.csproj", "{4CABA244-6123-4C61-90AB-F5FE20A8168A}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CF.Api.UnitTest", "src\CF.Api.UnitTest\CF.Api.UnitTest.csproj", "{AF09E52F-212E-4ED6-A815-217B49C8D837}" 21 | EndProject 22 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CF.Migrations", "src\CF.Migrations\CF.Migrations.csproj", "{348179D1-891E-4D2E-BA8A-24807E1223EE}" 23 | EndProject 24 | Global 25 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 26 | Debug|Any CPU = Debug|Any CPU 27 | Release|Any CPU = Release|Any CPU 28 | EndGlobalSection 29 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 30 | {AE02CD1D-9F37-495A-B32F-1317B2F42022}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {AE02CD1D-9F37-495A-B32F-1317B2F42022}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {AE02CD1D-9F37-495A-B32F-1317B2F42022}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {AE02CD1D-9F37-495A-B32F-1317B2F42022}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {40931CEC-045A-4E2F-8745-A76AD15FA53B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {40931CEC-045A-4E2F-8745-A76AD15FA53B}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {40931CEC-045A-4E2F-8745-A76AD15FA53B}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {40931CEC-045A-4E2F-8745-A76AD15FA53B}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {9F7F03FA-CD8C-436E-976F-AC624064E858}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {9F7F03FA-CD8C-436E-976F-AC624064E858}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {9F7F03FA-CD8C-436E-976F-AC624064E858}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {9F7F03FA-CD8C-436E-976F-AC624064E858}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {A981F9D2-ABEE-46C9-953D-1892E1E76BD5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {A981F9D2-ABEE-46C9-953D-1892E1E76BD5}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {A981F9D2-ABEE-46C9-953D-1892E1E76BD5}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {A981F9D2-ABEE-46C9-953D-1892E1E76BD5}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {6C787844-6222-4D34-B8ED-813A39E468EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {6C787844-6222-4D34-B8ED-813A39E468EA}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {6C787844-6222-4D34-B8ED-813A39E468EA}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {6C787844-6222-4D34-B8ED-813A39E468EA}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {4CABA244-6123-4C61-90AB-F5FE20A8168A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {4CABA244-6123-4C61-90AB-F5FE20A8168A}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {4CABA244-6123-4C61-90AB-F5FE20A8168A}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {4CABA244-6123-4C61-90AB-F5FE20A8168A}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {AF09E52F-212E-4ED6-A815-217B49C8D837}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {AF09E52F-212E-4ED6-A815-217B49C8D837}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {AF09E52F-212E-4ED6-A815-217B49C8D837}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {AF09E52F-212E-4ED6-A815-217B49C8D837}.Release|Any CPU.Build.0 = Release|Any CPU 58 | {348179D1-891E-4D2E-BA8A-24807E1223EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 59 | {348179D1-891E-4D2E-BA8A-24807E1223EE}.Debug|Any CPU.Build.0 = Debug|Any CPU 60 | {348179D1-891E-4D2E-BA8A-24807E1223EE}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {348179D1-891E-4D2E-BA8A-24807E1223EE}.Release|Any CPU.Build.0 = Release|Any CPU 62 | EndGlobalSection 63 | GlobalSection(SolutionProperties) = preSolution 64 | HideSolutionNode = FALSE 65 | EndGlobalSection 66 | GlobalSection(NestedProjects) = preSolution 67 | {40931CEC-045A-4E2F-8745-A76AD15FA53B} = {FAD9F9C1-F3EE-4881-8A71-67F4EB69B1AA} 68 | {9F7F03FA-CD8C-436E-976F-AC624064E858} = {FAD9F9C1-F3EE-4881-8A71-67F4EB69B1AA} 69 | {A981F9D2-ABEE-46C9-953D-1892E1E76BD5} = {FAD9F9C1-F3EE-4881-8A71-67F4EB69B1AA} 70 | {6C787844-6222-4D34-B8ED-813A39E468EA} = {FAD9F9C1-F3EE-4881-8A71-67F4EB69B1AA} 71 | EndGlobalSection 72 | GlobalSection(ExtensibilityGlobals) = postSolution 73 | SolutionGuid = {B8AAA169-2335-4252-AEC5-E5EE6A78E940} 74 | EndGlobalSection 75 | EndGlobal 76 | -------------------------------------------------------------------------------- /src/CF.Api/Controllers/CustomerController.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using Asp.Versioning; 3 | using CF.Api.Helpers; 4 | using CF.Customer.Application.Dtos; 5 | using CF.Customer.Application.Facades.Interfaces; 6 | using CF.Customer.Domain.Exceptions; 7 | using CorrelationId.Abstractions; 8 | using Microsoft.AspNetCore.Mvc; 9 | 10 | namespace CF.Api.Controllers; 11 | 12 | [ApiController] 13 | [ApiVersion("1.0")] 14 | [Route("api/v{version:apiVersion}/customer")] 15 | public class CustomerController( 16 | ICorrelationContextAccessor correlationContext, 17 | ILogger logger, 18 | ICustomerFacade customerFacade) : ControllerBase 19 | { 20 | [HttpGet] 21 | [ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any, VaryByQueryKeys = ["*"])] 22 | [ProducesResponseType(typeof(PaginationDto), (int)HttpStatusCode.OK)] 23 | public async Task>> Get( 24 | [FromQuery] CustomerFilterDto customerFilterDto, CancellationToken cancellationToken) 25 | { 26 | try 27 | { 28 | var result = await customerFacade.GetListByFilterAsync(customerFilterDto, cancellationToken); 29 | return result; 30 | } 31 | catch (ValidationException e) 32 | { 33 | if (logger.IsEnabled(LogLevel.Error)) 34 | logger.LogError(e, "Validation Exception Details. CorrelationId: {correlationId}", 35 | correlationContext.CorrelationContext.CorrelationId); 36 | 37 | return BadRequest(e.Message); 38 | } 39 | } 40 | 41 | [HttpGet("{id:long}")] 42 | [ResponseCache(Duration = 120, Location = ResponseCacheLocation.Any, VaryByQueryKeys = ["id"])] 43 | [ProducesResponseType((int)HttpStatusCode.BadRequest)] 44 | [ProducesResponseType((int)HttpStatusCode.NotFound)] 45 | [ProducesResponseType(typeof(CustomerResponseDto), (int)HttpStatusCode.OK)] 46 | public async Task> Get(long id, CancellationToken cancellationToken) 47 | { 48 | try 49 | { 50 | if (id <= 0) return BadRequest(ControllerHelper.CreateProblemDetails("Id", "Invalid Id.")); 51 | 52 | var filter = new CustomerFilterDto { Id = id }; 53 | var result = await customerFacade.GetByFilterAsync(filter, cancellationToken); 54 | 55 | if (result == null) return NotFound(); 56 | 57 | return result; 58 | } 59 | catch (ValidationException e) 60 | { 61 | if (logger.IsEnabled(LogLevel.Error)) 62 | logger.LogError(e, "Validation Exception. CorrelationId: {correlationId}", 63 | correlationContext.CorrelationContext.CorrelationId); 64 | 65 | return BadRequest(e.Message); 66 | } 67 | } 68 | 69 | [HttpPost] 70 | [ProducesResponseType((int)HttpStatusCode.BadRequest)] 71 | [ProducesResponseType((int)HttpStatusCode.Created)] 72 | public async Task Post([FromBody] CustomerRequestDto customerRequestDto, 73 | CancellationToken cancellationToken) 74 | { 75 | if (!ModelState.IsValid) return BadRequest(ModelState); 76 | 77 | var id = await customerFacade.CreateAsync(customerRequestDto, cancellationToken); 78 | 79 | return CreatedAtAction(nameof(Get), new { id, version = HttpContext.GetRequestedApiVersion()?.ToString() }, 80 | new { id }); 81 | } 82 | 83 | [HttpPut("{id:long}")] 84 | [ProducesResponseType((int)HttpStatusCode.BadRequest)] 85 | [ProducesResponseType((int)HttpStatusCode.NotFound)] 86 | [ProducesResponseType((int)HttpStatusCode.NoContent)] 87 | public async Task Put(long id, [FromBody] CustomerRequestDto customerRequestDto, 88 | CancellationToken cancellationToken) 89 | { 90 | try 91 | { 92 | if (!ModelState.IsValid) return BadRequest(ModelState); 93 | 94 | if (id <= 0) return BadRequest(ControllerHelper.CreateProblemDetails("Id", "Invalid Id.")); 95 | 96 | await customerFacade.UpdateAsync(id, customerRequestDto, cancellationToken); 97 | return NoContent(); 98 | } 99 | catch (EntityNotFoundException e) 100 | { 101 | if (logger.IsEnabled(LogLevel.Error)) 102 | logger.LogError(e, "Entity Not Found Exception. CorrelationId: {correlationId}", 103 | correlationContext.CorrelationContext.CorrelationId); 104 | 105 | return NotFound(); 106 | } 107 | catch (ValidationException e) 108 | { 109 | if (logger.IsEnabled(LogLevel.Error)) 110 | logger.LogError(e, "Validation Exception. CorrelationId: {correlationId}", 111 | correlationContext.CorrelationContext.CorrelationId); 112 | 113 | return BadRequest(e.Message); 114 | } 115 | } 116 | 117 | [HttpDelete("{id:long}")] 118 | [ProducesResponseType((int)HttpStatusCode.BadRequest)] 119 | [ProducesResponseType((int)HttpStatusCode.NotFound)] 120 | [ProducesResponseType((int)HttpStatusCode.NoContent)] 121 | public async Task Delete(long id, CancellationToken cancellationToken) 122 | { 123 | try 124 | { 125 | if (id <= 0) return BadRequest(ControllerHelper.CreateProblemDetails("Id", "Invalid Id.")); 126 | 127 | await customerFacade.DeleteAsync(id, cancellationToken); 128 | 129 | return NoContent(); 130 | } 131 | catch (EntityNotFoundException e) 132 | { 133 | if (logger.IsEnabled(LogLevel.Error)) 134 | logger.LogError(e, "Entity Not Found Exception. CorrelationId: {correlationId}", 135 | correlationContext.CorrelationContext.CorrelationId); 136 | 137 | return NotFound(); 138 | } 139 | catch (ValidationException e) 140 | { 141 | if (logger.IsEnabled(LogLevel.Error)) 142 | logger.LogError(e, "Validation Exception. CorrelationId: {correlationId}", 143 | correlationContext.CorrelationContext.CorrelationId); 144 | 145 | return BadRequest(e.Message); 146 | } 147 | } 148 | } -------------------------------------------------------------------------------- /src/CF.Api.UnitTest/CustomerControllerTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using Asp.Versioning; 6 | using CF.Api.Controllers; 7 | using CF.Customer.Application.Dtos; 8 | using CF.Customer.Application.Facades.Interfaces; 9 | using CorrelationId; 10 | using CorrelationId.Abstractions; 11 | using Microsoft.AspNetCore.Http; 12 | using Microsoft.AspNetCore.Mvc; 13 | using Microsoft.Extensions.Logging; 14 | using Moq; 15 | using Xunit; 16 | 17 | namespace CF.Api.UnitTest; 18 | 19 | public class CustomerControllerTest 20 | { 21 | private readonly CancellationTokenSource _cancellationTokenSource = new(); 22 | private readonly Mock _correlationContext = new(); 23 | private readonly Mock _customerFacade = new(); 24 | private readonly Mock> _logger = new(); 25 | 26 | public CustomerControllerTest() 27 | { 28 | _correlationContext.Setup(x => x.CorrelationContext) 29 | .Returns(new CorrelationContext(Guid.NewGuid().ToString(), "HeaderValue")); 30 | } 31 | 32 | [Fact] 33 | public async Task GetListTestAsync() 34 | { 35 | //Arrange 36 | var facadeResult = new PaginationDto 37 | { 38 | Count = 2, 39 | Result = 40 | [ 41 | new CustomerResponseDto 42 | { 43 | Email = "tarnished@test.com", 44 | FirstName = "Elden", 45 | Surname = "Ring", 46 | FullName = "Elden Ring", 47 | Id = 1 48 | }, 49 | new CustomerResponseDto 50 | { 51 | Email = "nameless_king@test.com", 52 | FirstName = "Elden", 53 | Surname = "King", 54 | FullName = "Elden King", 55 | Id = 2 56 | } 57 | ] 58 | }; 59 | 60 | _customerFacade 61 | .Setup(x => x.GetListByFilterAsync(It.IsAny(), _cancellationTokenSource.Token)) 62 | .ReturnsAsync(facadeResult); 63 | 64 | var controller = new CustomerController(_correlationContext.Object, _logger.Object, _customerFacade.Object); 65 | 66 | var requestDto = new CustomerFilterDto 67 | { 68 | FirstName = "Elden" 69 | }; 70 | 71 | //Act 72 | var actionResult = await controller.Get(requestDto, _cancellationTokenSource.Token); 73 | 74 | //Assert 75 | Assert.NotNull(actionResult); 76 | Assert.Equal(2, actionResult.Value?.Count); 77 | Assert.Equal(2, actionResult.Value?.Result.Count(x => x.FirstName == "Elden")); 78 | } 79 | 80 | [Fact] 81 | public async Task GetByIdTestAsync() 82 | { 83 | //Arrange 84 | var facadeResult = new CustomerResponseDto 85 | { 86 | Email = "tarnished@test.com", 87 | FirstName = "Elden", 88 | Surname = "Ring", 89 | FullName = "Elden Ring", 90 | Id = 1 91 | }; 92 | 93 | _customerFacade.Setup(x => x.GetByFilterAsync(It.IsAny(), _cancellationTokenSource.Token)) 94 | .ReturnsAsync(facadeResult); 95 | 96 | var controller = new CustomerController(_correlationContext.Object, _logger.Object, _customerFacade.Object); 97 | 98 | //Act 99 | var actionResult = await controller.Get(1, _cancellationTokenSource.Token); 100 | 101 | //Assert 102 | Assert.NotNull(actionResult); 103 | Assert.Equal(1, actionResult.Value?.Id); 104 | Assert.Equal("tarnished@test.com", actionResult.Value?.Email); 105 | } 106 | 107 | [Fact] 108 | public async Task PostTestAsync() 109 | { 110 | //Arrange 111 | _customerFacade.Setup(x => x.CreateAsync(It.IsAny(), _cancellationTokenSource.Token)) 112 | .ReturnsAsync(1); 113 | 114 | var controller = new CustomerController(_correlationContext.Object, _logger.Object, _customerFacade.Object); 115 | 116 | // Mock HttpContext for API versioning 117 | var httpContext = new DefaultHttpContext(); 118 | var apiVersion = new ApiVersion(1, 0); 119 | httpContext.Features.Set(new ApiVersioningFeature(httpContext) 120 | { 121 | RequestedApiVersion = apiVersion 122 | }); 123 | 124 | controller.ControllerContext = new ControllerContext 125 | { 126 | HttpContext = httpContext 127 | }; 128 | 129 | var requestDto = new CustomerRequestDto 130 | { 131 | ConfirmPassword = "123DarkSouls!", 132 | Password = "123DarkSouls!", 133 | Email = "chosen_one@test.com", 134 | FirstName = "Dark", 135 | Surname = "Souls" 136 | }; 137 | 138 | //Act 139 | var actionResult = await controller.Post(requestDto, _cancellationTokenSource.Token); 140 | 141 | //Assert 142 | Assert.NotNull(actionResult); 143 | var createdAtActionResult = Assert.IsType(actionResult); 144 | Assert.Equal(nameof(CustomerController.Get), createdAtActionResult.ActionName); 145 | Assert.NotNull(createdAtActionResult.RouteValues); 146 | Assert.True(createdAtActionResult.RouteValues.ContainsKey("id")); 147 | Assert.Equal(1L, createdAtActionResult.RouteValues["id"]); 148 | Assert.True(createdAtActionResult.RouteValues.ContainsKey("version")); 149 | Assert.Equal("1.0", createdAtActionResult.RouteValues["version"]); 150 | } 151 | 152 | [Fact] 153 | public async Task PutTestAsync() 154 | { 155 | //Arrange 156 | _customerFacade.Setup(x => 157 | x.UpdateAsync(It.IsAny(), It.IsAny(), _cancellationTokenSource.Token)); 158 | 159 | var controller = new CustomerController(_correlationContext.Object, _logger.Object, _customerFacade.Object); 160 | 161 | var requestDto = new CustomerRequestDto 162 | { 163 | ConfirmPassword = "123DarkSouls!", 164 | Password = "123DarkSouls!", 165 | Email = "chosen_one@test.com", 166 | FirstName = "Dark", 167 | Surname = "Souls" 168 | }; 169 | 170 | //Act 171 | var actionResult = await controller.Put(1, requestDto, _cancellationTokenSource.Token); 172 | 173 | //Assert 174 | Assert.NotNull(actionResult); 175 | Assert.IsType(actionResult); 176 | } 177 | 178 | [Fact] 179 | public async Task DeleteTestAsync() 180 | { 181 | //Arrange 182 | _customerFacade.Setup(x => x.DeleteAsync(It.IsAny(), _cancellationTokenSource.Token)); 183 | 184 | var controller = new CustomerController(_correlationContext.Object, _logger.Object, _customerFacade.Object); 185 | 186 | //Act 187 | var actionResult = await controller.Delete(1, _cancellationTokenSource.Token); 188 | 189 | //Assert 190 | Assert.NotNull(actionResult); 191 | Assert.IsType(actionResult); 192 | } 193 | } -------------------------------------------------------------------------------- /src/CF.Customer.UnitTest/Application/Facades/CustomerFacadeTest.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Application.Dtos; 2 | using CF.Customer.Application.Facades; 3 | using CF.Customer.Application.Mappers; 4 | using CF.Customer.Domain.Models; 5 | using CF.Customer.Domain.Services.Interfaces; 6 | using Moq; 7 | using Xunit; 8 | 9 | namespace CF.Customer.UnitTest.Application.Facades; 10 | 11 | public class CustomerFacadeTest 12 | { 13 | private readonly CancellationTokenSource _cancellationTokenSource = new(); 14 | private readonly Mock _mockMapper = new(); 15 | private readonly Mock _mockService = new(); 16 | 17 | [Fact] 18 | public async Task CreateTestAsync() 19 | { 20 | // Arrange 21 | var customer = CreateCustomer(); 22 | var customerRequestDto = CreateCustomerRequestDto(); 23 | const long id = 1; 24 | 25 | _mockMapper.Setup(x => x.MapToCustomer(customerRequestDto)).Returns(customer); 26 | _mockService.Setup(x => x.CreateAsync(customer, _cancellationTokenSource.Token)).ReturnsAsync(id); 27 | var mockFacade = new CustomerFacade(_mockService.Object, _mockMapper.Object); 28 | 29 | // Act 30 | var result = await mockFacade.CreateAsync(customerRequestDto, _cancellationTokenSource.Token); 31 | 32 | // Assert 33 | Assert.Equal(id, result); 34 | _mockService.Verify( 35 | x => x.CreateAsync(It.IsAny(), _cancellationTokenSource.Token), 36 | Times.Once); 37 | _mockMapper.Verify(x => x.MapToCustomer(customerRequestDto), Times.Once); 38 | } 39 | 40 | [Fact] 41 | public async Task GetTestAsync() 42 | { 43 | // Arrange 44 | var customer = CreateCustomer(); 45 | var customerResponseDto = CreateCustomerResponseDto(); 46 | 47 | var filterDto = new CustomerFilterDto { Id = 1 }; 48 | var filter = new CustomerFilter { Id = 1 }; 49 | 50 | _mockMapper.Setup(x => x.MapToCustomerResponseDto(customer)).Returns(customerResponseDto); 51 | _mockMapper.Setup(x => x.MapToCustomerFilter(filterDto)).Returns(filter); 52 | _mockService.Setup(x => x.GetByFilterAsync(filter, _cancellationTokenSource.Token)).ReturnsAsync(customer); 53 | var mockFacade = new CustomerFacade(_mockService.Object, _mockMapper.Object); 54 | 55 | // Act 56 | var result = await mockFacade.GetByFilterAsync(filterDto, _cancellationTokenSource.Token); 57 | 58 | // Assert 59 | Assert.Equal(customer.Id, result.Id); 60 | _mockService.Verify(x => x.GetByFilterAsync(It.IsAny(), _cancellationTokenSource.Token), 61 | Times.Once); 62 | _mockMapper.Verify(x => x.MapToCustomerFilter(filterDto), Times.Once); 63 | } 64 | 65 | [Fact] 66 | public async Task GetListTestAsync() 67 | { 68 | // Arrange 69 | var customers = new List 70 | { 71 | CreateCustomer(), 72 | CreateCustomer(2) 73 | }; 74 | var pagination = CreatePagination(customers); 75 | 76 | var customersDto = new List 77 | { 78 | CreateCustomerResponseDto(), 79 | CreateCustomerResponseDto(2) 80 | }; 81 | var paginationDto = CreatePaginationDto(customersDto); 82 | 83 | var filterDto = new CustomerFilterDto { Id = 1 }; 84 | var filter = new CustomerFilter { Id = 1 }; 85 | 86 | _mockMapper.Setup(x => x.MapToCustomerFilter(filterDto)).Returns(filter); 87 | _mockMapper.Setup(x => x.MapToPaginationDto(pagination)).Returns(paginationDto); 88 | _mockService.Setup(x => x.GetListByFilterAsync(filter, _cancellationTokenSource.Token)) 89 | .ReturnsAsync(pagination); 90 | var mockFacade = new CustomerFacade(_mockService.Object, _mockMapper.Object); 91 | 92 | // Act 93 | var result = await mockFacade.GetListByFilterAsync(filterDto, _cancellationTokenSource.Token); 94 | 95 | // Assert 96 | Assert.Equal(paginationDto.Count, result.Count); 97 | _mockService.Verify(x => x.GetListByFilterAsync(It.IsAny(), _cancellationTokenSource.Token), 98 | Times.Once); 99 | _mockMapper.Verify(x => x.MapToCustomerFilter(filterDto), Times.Once); 100 | _mockMapper.Verify(x => x.MapToPaginationDto(pagination), Times.Once); 101 | } 102 | 103 | [Fact] 104 | public async Task UpdateTestAsync() 105 | { 106 | // Arrange 107 | var customerRequestDto = CreateCustomerRequestDto(); 108 | var customer = CreateCustomer(); 109 | const long id = 1; 110 | 111 | _mockMapper.Setup(x => x.MapToCustomer(customerRequestDto)).Returns(customer); 112 | var mockFacade = new CustomerFacade(_mockService.Object, _mockMapper.Object); 113 | 114 | // Act 115 | var exception = await Record.ExceptionAsync(() => 116 | mockFacade.UpdateAsync(id, customerRequestDto, _cancellationTokenSource.Token)); 117 | 118 | // Assert 119 | Assert.Null(exception); 120 | _mockMapper.Verify(x => x.MapToCustomer(customerRequestDto), Times.Once); 121 | } 122 | 123 | [Fact] 124 | public async Task DeleteTestAsync() 125 | { 126 | // Arrange 127 | const long id = 1; 128 | var mockFacade = new CustomerFacade(_mockService.Object, _mockMapper.Object); 129 | 130 | // Act 131 | var exception = await Record.ExceptionAsync(() => mockFacade.DeleteAsync(id, _cancellationTokenSource.Token)); 132 | 133 | // Assert 134 | Assert.Null(exception); 135 | } 136 | 137 | private static PaginationDto CreatePaginationDto(List customersDto) 138 | { 139 | return new PaginationDto 140 | { 141 | PageSize = 10, 142 | CurrentPage = 1, 143 | Count = 2, 144 | TotalPages = 1, 145 | Result = customersDto 146 | }; 147 | } 148 | 149 | private static Pagination CreatePagination( 150 | List customers) 151 | { 152 | return new Pagination 153 | { 154 | PageSize = 10, 155 | CurrentPage = 1, 156 | Count = 2, 157 | Result = customers 158 | }; 159 | } 160 | 161 | private static CustomerRequestDto CreateCustomerRequestDto() 162 | { 163 | return new CustomerRequestDto 164 | { 165 | Email = "test1@test.com", 166 | Surname = "Surname", 167 | FirstName = "First Name", 168 | Password = "P@013333343", 169 | ConfirmPassword = "P@013333343" 170 | }; 171 | } 172 | 173 | private static Customer.Domain.Entities.Customer CreateCustomer(int id = 1) 174 | { 175 | return new Customer.Domain.Entities.Customer 176 | { 177 | Id = id, 178 | Password = "P@013333343", 179 | Email = "test1@test.com", 180 | Surname = "Surname", 181 | FirstName = "First Name" 182 | }; 183 | } 184 | 185 | private static CustomerResponseDto CreateCustomerResponseDto(int id = 1) 186 | { 187 | return new CustomerResponseDto 188 | { 189 | Id = id, 190 | Email = "test1@test.com", 191 | Surname = "Surname", 192 | FirstName = "First Name", 193 | FullName = "First Name Surname" 194 | }; 195 | } 196 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | 33 | # Visual Studio 2015/2017 cache/options directory 34 | .vs/ 35 | # Uncomment if you have tasks that create the project's static files in wwwroot 36 | #wwwroot/ 37 | 38 | # Visual Studio 2017 auto generated files 39 | Generated\ Files/ 40 | 41 | # MSTest test Results 42 | [Tt]est[Rr]esult*/ 43 | [Bb]uild[Ll]og.* 44 | 45 | # NUnit 46 | *.VisualState.xml 47 | TestResult.xml 48 | nunit-*.xml 49 | 50 | # Build Results of an ATL Project 51 | [Dd]ebugPS/ 52 | [Rr]eleasePS/ 53 | dlldata.c 54 | 55 | # Benchmark Results 56 | BenchmarkDotNet.Artifacts/ 57 | 58 | # .NET Core 59 | project.lock.json 60 | project.fragment.lock.json 61 | artifacts/ 62 | 63 | # StyleCop 64 | StyleCopReport.xml 65 | 66 | # Files built by Visual Studio 67 | *_i.c 68 | *_p.c 69 | *_h.h 70 | *.ilk 71 | *.meta 72 | *.obj 73 | *.iobj 74 | *.pch 75 | *.pdb 76 | *.ipdb 77 | *.pgc 78 | *.pgd 79 | *.rsp 80 | *.sbr 81 | *.tlb 82 | *.tli 83 | *.tlh 84 | *.tmp 85 | *.tmp_proj 86 | *_wpftmp.csproj 87 | *.log 88 | *.vspscc 89 | *.vssscc 90 | .builds 91 | *.pidb 92 | *.svclog 93 | *.scc 94 | 95 | # Chutzpah Test files 96 | _Chutzpah* 97 | 98 | # Visual C++ cache files 99 | ipch/ 100 | *.aps 101 | *.ncb 102 | *.opendb 103 | *.opensdf 104 | *.sdf 105 | *.cachefile 106 | *.VC.db 107 | *.VC.VC.opendb 108 | 109 | # Visual Studio profiler 110 | *.psess 111 | *.vsp 112 | *.vspx 113 | *.sap 114 | 115 | # Visual Studio Trace Files 116 | *.e2e 117 | 118 | # TFS 2012 Local Workspace 119 | $tf/ 120 | 121 | # Guidance Automation Toolkit 122 | *.gpState 123 | 124 | # ReSharper is a .NET coding add-in 125 | _ReSharper*/ 126 | *.[Rr]e[Ss]harper 127 | *.DotSettings.user 128 | 129 | # JustCode is a .NET coding add-in 130 | .JustCode 131 | 132 | # TeamCity is a build add-in 133 | _TeamCity* 134 | 135 | # DotCover is a Code Coverage Tool 136 | *.dotCover 137 | 138 | # AxoCover is a Code Coverage Tool 139 | .axoCover/* 140 | !.axoCover/settings.json 141 | 142 | # Visual Studio code coverage results 143 | *.coverage 144 | *.coveragexml 145 | 146 | # NCrunch 147 | _NCrunch_* 148 | .*crunch*.local.xml 149 | nCrunchTemp_* 150 | 151 | # MightyMoose 152 | *.mm.* 153 | AutoTest.Net/ 154 | 155 | # Web workbench (sass) 156 | .sass-cache/ 157 | 158 | # Installshield output folder 159 | [Ee]xpress/ 160 | 161 | # DocProject is a documentation generator add-in 162 | DocProject/buildhelp/ 163 | DocProject/Help/*.HxT 164 | DocProject/Help/*.HxC 165 | DocProject/Help/*.hhc 166 | DocProject/Help/*.hhk 167 | DocProject/Help/*.hhp 168 | DocProject/Help/Html2 169 | DocProject/Help/html 170 | 171 | # Click-Once directory 172 | publish/ 173 | 174 | # Publish Web Output 175 | *.[Pp]ublish.xml 176 | *.azurePubxml 177 | # Note: Comment the next line if you want to checkin your web deploy settings, 178 | # but database connection strings (with potential passwords) will be unencrypted 179 | *.pubxml 180 | *.publishproj 181 | 182 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 183 | # checkin your Azure Web App publish settings, but sensitive information contained 184 | # in these scripts will be unencrypted 185 | PublishScripts/ 186 | 187 | # NuGet Packages 188 | *.nupkg 189 | # NuGet Symbol Packages 190 | *.snupkg 191 | # The packages folder can be ignored because of Package Restore 192 | **/[Pp]ackages/* 193 | # except build/, which is used as an MSBuild target. 194 | !**/[Pp]ackages/build/ 195 | # Uncomment if necessary however generally it will be regenerated when needed 196 | #!**/[Pp]ackages/repositories.config 197 | # NuGet v3's project.json files produces more ignorable files 198 | *.nuget.props 199 | *.nuget.targets 200 | 201 | # Microsoft Azure Build Output 202 | csx/ 203 | *.build.csdef 204 | 205 | # Microsoft Azure Emulator 206 | ecf/ 207 | rcf/ 208 | 209 | # Windows Store app package directories and files 210 | AppPackages/ 211 | BundleArtifacts/ 212 | Package.StoreAssociation.xml 213 | _pkginfo.txt 214 | *.appx 215 | *.appxbundle 216 | *.appxupload 217 | 218 | # Visual Studio cache files 219 | # files ending in .cache can be ignored 220 | *.[Cc]ache 221 | # but keep track of directories ending in .cache 222 | !?*.[Cc]ache/ 223 | 224 | # Others 225 | ClientBin/ 226 | ~$* 227 | *~ 228 | *.dbmdl 229 | *.dbproj.schemaview 230 | *.jfm 231 | *.pfx 232 | *.publishsettings 233 | orleans.codegen.cs 234 | 235 | # Including strong name files can present a security risk 236 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 237 | #*.snk 238 | 239 | # Since there are multiple workflows, uncomment next line to ignore bower_components 240 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 241 | #bower_components/ 242 | 243 | # RIA/Silverlight projects 244 | Generated_Code/ 245 | 246 | # Backup & report files from converting an old project file 247 | # to a newer Visual Studio version. Backup files are not needed, 248 | # because we have git ;-) 249 | _UpgradeReport_Files/ 250 | Backup*/ 251 | UpgradeLog*.XML 252 | UpgradeLog*.htm 253 | ServiceFabricBackup/ 254 | *.rptproj.bak 255 | 256 | # SQL Server files 257 | *.mdf 258 | *.ldf 259 | *.ndf 260 | 261 | # Business Intelligence projects 262 | *.rdl.data 263 | *.bim.layout 264 | *.bim_*.settings 265 | *.rptproj.rsuser 266 | *- [Bb]ackup.rdl 267 | *- [Bb]ackup ([0-9]).rdl 268 | *- [Bb]ackup ([0-9][0-9]).rdl 269 | 270 | # Microsoft Fakes 271 | FakesAssemblies/ 272 | 273 | # GhostDoc plugin setting file 274 | *.GhostDoc.xml 275 | 276 | # Node.js Tools for Visual Studio 277 | .ntvs_analysis.dat 278 | node_modules/ 279 | 280 | # Visual Studio 6 build log 281 | *.plg 282 | 283 | # Visual Studio 6 workspace options file 284 | *.opt 285 | 286 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 287 | *.vbw 288 | 289 | # Visual Studio LightSwitch build output 290 | **/*.HTMLClient/GeneratedArtifacts 291 | **/*.DesktopClient/GeneratedArtifacts 292 | **/*.DesktopClient/ModelManifest.xml 293 | **/*.Server/GeneratedArtifacts 294 | **/*.Server/ModelManifest.xml 295 | _Pvt_Extensions 296 | 297 | # Paket dependency manager 298 | .paket/paket.exe 299 | paket-files/ 300 | 301 | # FAKE - F# Make 302 | .fake/ 303 | 304 | # CodeRush personal settings 305 | .cr/personal 306 | 307 | # Python Tools for Visual Studio (PTVS) 308 | __pycache__/ 309 | *.pyc 310 | 311 | # Cake - Uncomment if you are using it 312 | # tools/** 313 | # !tools/packages.config 314 | 315 | # Tabs Studio 316 | *.tss 317 | 318 | # Telerik's JustMock configuration file 319 | *.jmconfig 320 | 321 | # BizTalk build output 322 | *.btp.cs 323 | *.btm.cs 324 | *.odx.cs 325 | *.xsd.cs 326 | 327 | # OpenCover UI analysis results 328 | OpenCover/ 329 | 330 | # Azure Stream Analytics local run output 331 | ASALocalRun/ 332 | 333 | # MSBuild Binary and Structured Log 334 | *.binlog 335 | 336 | # NVidia Nsight GPU debugger configuration file 337 | *.nvuser 338 | 339 | # MFractors (Xamarin productivity tool) working folder 340 | .mfractor/ 341 | 342 | # Local History for Visual Studio 343 | .localhistory/ 344 | 345 | # BeatPulse healthcheck temp database 346 | healthchecksdb 347 | 348 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 349 | MigrationBackup/ 350 | 351 | #Rider 352 | .idea -------------------------------------------------------------------------------- /src/CF.Customer.UnitTest/Domain/Entities/CustomerTest.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Domain.Entities; 2 | using CF.Customer.Domain.Exceptions; 3 | using Xunit; 4 | 5 | namespace CF.Customer.UnitTest.Domain.Entities; 6 | 7 | public class CustomerTest 8 | { 9 | [Theory] 10 | [InlineData("1894")] 11 | [InlineData("AA189412")] 12 | [InlineData("AABCSSDSD")] 13 | [InlineData("wedededwe")] 14 | [InlineData("wedeAAAAA")] 15 | [InlineData("aa189412")] 16 | [InlineData("@@189412")] 17 | [InlineData("@abcdefg")] 18 | [InlineData("@AASDFEF")] 19 | [InlineData("12345678")] 20 | [InlineData("@@@!@!@!@")] 21 | [InlineData("1123@aA")] 22 | [InlineData("1123aaswdewwpfomwfpo4")] 23 | public void InvalidPasswordRequirementsTest(string password) 24 | { 25 | // Arrange 26 | var customer = new Customer.Domain.Entities.Customer 27 | { 28 | Password = password 29 | }; 30 | 31 | const string invalidPasswordErrorMessage = 32 | "Password must be at least 8 characters and contain at 3 of the following: upper case (A-Z), lower case (a-z), number (0-9) and special character (e.g. !@#$%^&*)."; 33 | 34 | // Act 35 | var exception = Assert.Throws(customer.ValidatePassword); 36 | 37 | // Assert 38 | Assert.Equal(invalidPasswordErrorMessage, exception.Message); 39 | } 40 | 41 | [Fact] 42 | public void ValidPasswordRequirementsTest() 43 | { 44 | //Arrange 45 | var customer = new Customer.Domain.Entities.Customer 46 | { 47 | Password = "P@ssWord1" 48 | }; 49 | 50 | //Act 51 | var exception = Record.Exception(customer.ValidatePassword); 52 | 53 | //Assert 54 | Assert.Null(exception); 55 | } 56 | 57 | [Theory] 58 | [InlineData("1894@")] 59 | [InlineData("aaa@com. ")] 60 | [InlineData("aaa@@.com ")] 61 | [InlineData("aaa @gmail.com")] 62 | [InlineData("aaa @gmail")] 63 | [InlineData("aaa@gmail.com ")] 64 | [InlineData("@gmail.com")] 65 | public void InvalidEmailFormatTest(string email) 66 | { 67 | //Arrange 68 | var customer = new Customer.Domain.Entities.Customer 69 | { 70 | Email = email 71 | }; 72 | 73 | const string invalidEmailFormatErrorMessage = "The Email is not a valid e-mail address."; 74 | 75 | //Act 76 | var exception = Assert.Throws(customer.ValidateEmail); 77 | 78 | //Assert 79 | Assert.Equal(invalidEmailFormatErrorMessage, exception.Message); 80 | } 81 | 82 | [Fact] 83 | public void InvalidEmailRequiredTest() 84 | { 85 | //Arrange 86 | var customer = new Customer.Domain.Entities.Customer 87 | { 88 | Email = string.Empty 89 | }; 90 | 91 | const string invalidEmailFormatErrorMessage = "The Email is required."; 92 | 93 | //Act 94 | var exception = Assert.Throws(customer.ValidateEmail); 95 | 96 | //Assert 97 | Assert.Equal(invalidEmailFormatErrorMessage, exception.Message); 98 | } 99 | 100 | [Fact] 101 | public void ValidEmailTest() 102 | { 103 | //Arrange 104 | var customer = new Customer.Domain.Entities.Customer 105 | { 106 | Email = "valdivia@gmail.com" 107 | }; 108 | 109 | //Act 110 | var exception = Record.Exception(customer.ValidateEmail); 111 | 112 | //Assert 113 | Assert.Null(exception); 114 | } 115 | 116 | [Theory] 117 | [InlineData("a")] 118 | [InlineData( 119 | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaawwwwwwwwwwwwwwwwwwwwwwwwwwwwwwewewe")] 120 | public void InvalidFirstNameTest(string firstName) 121 | { 122 | //Arrange 123 | var customer = new Customer.Domain.Entities.Customer 124 | { 125 | FirstName = firstName 126 | }; 127 | 128 | const string invalidFirstName = 129 | "The First Name must be a string with a minimum length of 2 and a maximum length of 100."; 130 | 131 | //Act 132 | var exception = Assert.Throws(customer.ValidateFirstName); 133 | 134 | //Assert 135 | Assert.Equal(invalidFirstName, exception.Message); 136 | } 137 | 138 | [Fact] 139 | public void ValidFirstNameTest() 140 | { 141 | //Arrange 142 | var customer = new Customer.Domain.Entities.Customer 143 | { 144 | FirstName = "Valdivia" 145 | }; 146 | 147 | //Act 148 | var exception = Record.Exception(customer.ValidateFirstName); 149 | 150 | //Assert 151 | Assert.Null(exception); 152 | } 153 | 154 | [Fact] 155 | public void InvalidFirstNameRequiredTest() 156 | { 157 | //Arrange 158 | var customer = new Customer.Domain.Entities.Customer 159 | { 160 | FirstName = string.Empty 161 | }; 162 | 163 | const string invalidEmailFormatErrorMessage = "The First Name is required."; 164 | 165 | //Act 166 | var exception = Assert.Throws(customer.ValidateFirstName); 167 | 168 | //Assert 169 | Assert.Equal(invalidEmailFormatErrorMessage, exception.Message); 170 | } 171 | 172 | [Theory] 173 | [InlineData("a")] 174 | [InlineData( 175 | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaawwwwwwwwwwwwwwwwwwwwwwwwwwwwwwewewe")] 176 | public void InvalidSurnameTest(string surname) 177 | { 178 | //Arrange 179 | var customer = new Customer.Domain.Entities.Customer 180 | { 181 | Surname = surname 182 | }; 183 | 184 | const string invalidSurname = 185 | "The Surname must be a string with a minimum length of 2 and a maximum length of 100."; 186 | 187 | //Act 188 | var exception = Assert.Throws(customer.ValidateSurname); 189 | 190 | //Assert 191 | Assert.Equal(invalidSurname, exception.Message); 192 | } 193 | 194 | [Fact] 195 | public void ValidSurnameTest() 196 | { 197 | //Arrange 198 | var customer = new Customer.Domain.Entities.Customer 199 | { 200 | Surname = "Valdivia" 201 | }; 202 | 203 | //Act 204 | var exception = Record.Exception(customer.ValidateSurname); 205 | 206 | //Assert 207 | Assert.Null(exception); 208 | } 209 | 210 | [Fact] 211 | public void InvalidSurnameRequiredTest() 212 | { 213 | //Arrange 214 | var customer = new Customer.Domain.Entities.Customer 215 | { 216 | Surname = string.Empty 217 | }; 218 | 219 | const string invalidEmailFormatErrorMessage = "The Surname is required."; 220 | 221 | //Act 222 | var exception = Assert.Throws(customer.ValidateSurname); 223 | 224 | //Assert 225 | Assert.Equal(invalidEmailFormatErrorMessage, exception.Message); 226 | } 227 | 228 | [Fact] 229 | public void GetFullName() 230 | { 231 | //Arrange 232 | var customer = new Customer.Domain.Entities.Customer 233 | { 234 | FirstName = "Valdivia", 235 | Surname = "El Mago" 236 | }; 237 | 238 | //Act 239 | var result = customer.GetFullName(); 240 | 241 | //Assert 242 | Assert.Equal("Valdivia El Mago", result); 243 | } 244 | 245 | [Fact] 246 | public void SetCreatedDate() 247 | { 248 | //Arrange 249 | var customer = new Customer.Domain.Entities.Customer(); 250 | var actualDate = DateTime.UtcNow; 251 | 252 | //Act 253 | customer.SetCreatedDate(); 254 | 255 | //Assert 256 | Assert.True(customer.Created >= actualDate); 257 | } 258 | 259 | [Fact] 260 | public void SetUpdatedDate() 261 | { 262 | //Arrange 263 | var customer = new Customer.Domain.Entities.Customer(); 264 | 265 | //Act 266 | customer.SetUpdatedDate(); 267 | 268 | //Assert 269 | Assert.NotNull(customer.Updated); 270 | } 271 | } -------------------------------------------------------------------------------- /src/CF.Api/Program.cs: -------------------------------------------------------------------------------- 1 | using System.IO.Compression; 2 | using System.Text.Json; 3 | using System.Threading.RateLimiting; 4 | using Asp.Versioning; 5 | using CF.Api.Filters; 6 | using CF.Api.Middleware; 7 | using CF.Customer.Application.Facades; 8 | using CF.Customer.Application.Facades.Interfaces; 9 | using CF.Customer.Application.Mappers; 10 | using CF.Customer.Domain.Repositories; 11 | using CF.Customer.Domain.Services; 12 | using CF.Customer.Domain.Services.Interfaces; 13 | using CF.Customer.Infrastructure.DbContext; 14 | using CF.Customer.Infrastructure.Mappers; 15 | using CF.Customer.Infrastructure.Repositories; 16 | using CorrelationId; 17 | using CorrelationId.DependencyInjection; 18 | using Microsoft.AspNetCore.Diagnostics.HealthChecks; 19 | using Microsoft.AspNetCore.ResponseCompression; 20 | using Microsoft.EntityFrameworkCore; 21 | using Microsoft.Extensions.Diagnostics.HealthChecks; 22 | using NLog.Web; 23 | using Scalar.AspNetCore; 24 | using LogLevel = Microsoft.Extensions.Logging.LogLevel; 25 | 26 | var builder = WebApplication.CreateBuilder(args); 27 | 28 | builder.Host.UseNLog(); 29 | 30 | builder.Services.AddControllers(x => x.Filters.Add()); 31 | builder.Services.AddProblemDetails(); 32 | builder.Services.AddDefaultCorrelationId(ConfigureCorrelationId()); 33 | builder.Services.AddTransient(); 34 | builder.Services.AddTransient(); 35 | builder.Services.AddTransient(); 36 | builder.Services.AddTransient(); 37 | builder.Services.AddSingleton(); 38 | builder.Services.AddEndpointsApiExplorer(); 39 | builder.Services.AddOpenApi(); 40 | builder.Services.Configure(options => options.Level = CompressionLevel.Optimal); 41 | builder.Services.AddResponseCompression(options => { options.Providers.Add(); }); 42 | builder.Services.AddResponseCaching(); 43 | builder.Services.AddMemoryCache(); 44 | AddRateLimiting(); 45 | AddApiVersioning(); 46 | AddDbContext(); 47 | AddHealthChecks(); 48 | await using var app = builder.Build(); 49 | 50 | RunMigration(); 51 | app.UseRateLimiter(); 52 | app.UseCorrelationId(); 53 | AddExceptionHandler(); 54 | AddOpenApi(); 55 | app.UseMiddleware(); 56 | app.UseMiddleware(); 57 | app.UseMiddleware(); 58 | app.UseResponseCaching(); 59 | app.UseHttpsRedirection(); 60 | app.MapControllers(); 61 | MapHealthChecks(); 62 | 63 | await app.RunAsync(); 64 | 65 | void AddExceptionHandler() 66 | { 67 | if (app.Environment.IsDevelopment()) return; 68 | app.UseExceptionHandler(ConfigureExceptionHandler()); 69 | } 70 | 71 | void AddOpenApi() 72 | { 73 | if (!app.Environment.IsDevelopment()) return; 74 | app.MapOpenApi(); 75 | app.MapScalarApiReference(); 76 | } 77 | 78 | void AddRateLimiting() 79 | { 80 | var rateLimitConfig = builder.Configuration.GetSection("RateLimiting"); 81 | var permitLimit = rateLimitConfig.GetValue("PermitLimit", 60); 82 | var windowSeconds = rateLimitConfig.GetValue("WindowSeconds", 60); 83 | 84 | builder.Services.AddRateLimiter(options => 85 | { 86 | options.GlobalLimiter = PartitionedRateLimiter.Create(context => 87 | { 88 | var clientId = context.Connection.RemoteIpAddress?.ToString() ?? "anonymous"; 89 | 90 | return RateLimitPartition.GetFixedWindowLimiter(clientId, _ => new FixedWindowRateLimiterOptions 91 | { 92 | PermitLimit = permitLimit, 93 | Window = TimeSpan.FromSeconds(windowSeconds), 94 | QueueProcessingOrder = QueueProcessingOrder.OldestFirst, 95 | QueueLimit = 0 96 | }); 97 | }); 98 | 99 | options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; 100 | options.OnRejected = async (context, cancellationToken) => 101 | { 102 | context.HttpContext.Response.StatusCode = StatusCodes.Status429TooManyRequests; 103 | context.HttpContext.Response.ContentType = "application/json"; 104 | 105 | var response = new 106 | { 107 | statusCode = 429, 108 | message = $"Rate limit exceeded. Maximum {permitLimit} requests per {windowSeconds} seconds allowed.", 109 | retryAfter = context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter) 110 | ? retryAfter.TotalSeconds 111 | : windowSeconds 112 | }; 113 | 114 | await context.HttpContext.Response.WriteAsJsonAsync(response, cancellationToken); 115 | }; 116 | }); 117 | } 118 | 119 | void AddApiVersioning() 120 | { 121 | builder.Services.AddApiVersioning(options => 122 | { 123 | options.DefaultApiVersion = new ApiVersion(1, 0); 124 | options.AssumeDefaultVersionWhenUnspecified = true; 125 | options.ReportApiVersions = true; 126 | options.ApiVersionReader = new UrlSegmentApiVersionReader(); 127 | }).AddMvc().AddApiExplorer(options => 128 | { 129 | options.GroupNameFormat = "'v'VVV"; 130 | options.SubstituteApiVersionInUrl = true; 131 | }); 132 | } 133 | 134 | void AddDbContext() 135 | { 136 | if (builder.Environment.EnvironmentName.Contains("Test")) return; 137 | 138 | builder.Services.AddDbContext(options => 139 | { 140 | options.UseSqlServer(builder.Configuration.GetConnectionString("DbConnection"), 141 | a => { a.MigrationsAssembly("CF.Migrations"); }); 142 | }); 143 | } 144 | 145 | void AddHealthChecks() 146 | { 147 | builder.Services.AddHealthChecks(); 148 | 149 | if (builder.Environment.EnvironmentName.Contains("Test")) return; 150 | 151 | builder.Services.AddHealthChecks() 152 | .AddDbContextCheck("database", HealthStatus.Unhealthy, ["db", "sql"]) 153 | .AddCheck("self", () => HealthCheckResult.Healthy("API is running"), ["api"]); 154 | } 155 | 156 | void MapHealthChecks() 157 | { 158 | app.MapHealthChecks("/health", new HealthCheckOptions 159 | { 160 | Predicate = _ => true, 161 | ResponseWriter = async (context, report) => 162 | { 163 | context.Response.ContentType = "application/json"; 164 | var result = JsonSerializer.Serialize(new 165 | { 166 | status = report.Status.ToString(), 167 | checks = report.Entries.Select(e => new 168 | { 169 | name = e.Key, 170 | status = e.Value.Status.ToString(), 171 | description = e.Value.Description, 172 | duration = e.Value.Duration.TotalMilliseconds 173 | }), 174 | totalDuration = report.TotalDuration.TotalMilliseconds 175 | }); 176 | await context.Response.WriteAsync(result); 177 | } 178 | }); 179 | 180 | app.MapHealthChecks("/health/ready", new HealthCheckOptions 181 | { 182 | Predicate = check => check.Tags.Contains("db") 183 | }); 184 | 185 | app.MapHealthChecks("/health/live", new HealthCheckOptions 186 | { 187 | Predicate = check => check.Tags.Contains("api") 188 | }); 189 | } 190 | 191 | static Action ConfigureCorrelationId() 192 | { 193 | return options => 194 | { 195 | options.LogLevelOptions = new CorrelationIdLogLevelOptions 196 | { 197 | FoundCorrelationIdHeader = LogLevel.Debug, 198 | MissingCorrelationIdHeader = LogLevel.Debug 199 | }; 200 | }; 201 | } 202 | 203 | static Action ConfigureExceptionHandler() 204 | { 205 | return exceptionHandlerApp => 206 | { 207 | exceptionHandlerApp.Run(async context => 208 | { 209 | context.Response.StatusCode = StatusCodes.Status500InternalServerError; 210 | 211 | await context.Response.WriteAsJsonAsync(new 212 | { 213 | Message = "An unexpected internal exception occurred." 214 | }); 215 | }); 216 | }; 217 | } 218 | 219 | void RunMigration() 220 | { 221 | using var serviceScope = app.Services.GetRequiredService().CreateScope(); 222 | 223 | if (!serviceScope.ServiceProvider.GetRequiredService().Database.GetPendingMigrations() 224 | .Any()) return; 225 | 226 | serviceScope.ServiceProvider.GetRequiredService().Database.Migrate(); 227 | } 228 | 229 | public partial class Program; -------------------------------------------------------------------------------- /src/CF.Customer.UnitTest/Infrastructure/Repositories/CustomerRepositoryTest.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Common; 2 | using CF.Customer.Domain.Models; 3 | using CF.Customer.Infrastructure.DbContext; 4 | using CF.Customer.Infrastructure.Repositories; 5 | using Microsoft.Data.Sqlite; 6 | using Microsoft.EntityFrameworkCore; 7 | using Xunit; 8 | 9 | namespace CF.Customer.UnitTest.Infrastructure.Repositories; 10 | 11 | public class CustomerRepositoryTest 12 | { 13 | private readonly CancellationTokenSource _cancellationTokenSource = new(); 14 | 15 | [Fact] 16 | public async Task GetListTestAsync() 17 | { 18 | await using var connection = await CreateAndOpenSqliteConnectionAsync(); 19 | 20 | var options = await SetDbContextOptionsBuilderAsync(connection); 21 | 22 | await using var context = new CustomerContext(options); 23 | Assert.True(await context.Database.EnsureCreatedAsync()); 24 | 25 | //Arrange 26 | var customerOne = CreateCustomer(); 27 | var customerTwo = CreateCustomer(); 28 | customerTwo.Email = "email2@test.com"; 29 | 30 | //Act 31 | var repository = new CustomerRepository(context); 32 | await repository.AddRangeAsync([customerOne, customerTwo]); 33 | await repository.SaveChangesAsync(_cancellationTokenSource.Token); 34 | 35 | var filter = new CustomerFilter { FirstName = "FirstName" }; 36 | var result = await repository.GetListByFilterAsync(filter, _cancellationTokenSource.Token); 37 | 38 | //Assert 39 | Assert.Equal(2, result.Count); 40 | } 41 | 42 | [Fact] 43 | public async Task GetTestAsync() 44 | { 45 | await using var connection = await CreateAndOpenSqliteConnectionAsync(); 46 | var options = await SetDbContextOptionsBuilderAsync(connection); 47 | 48 | await using var context = new CustomerContext(options); 49 | Assert.True(await context.Database.EnsureCreatedAsync()); 50 | 51 | //Arrange 52 | var customerOne = CreateCustomer(); 53 | 54 | var repository = new CustomerRepository(context); 55 | repository.Add(customerOne); 56 | await repository.SaveChangesAsync(_cancellationTokenSource.Token); 57 | 58 | var filter = new CustomerFilter { Email = "test1@test.com" }; 59 | 60 | //Act 61 | var result = await repository.GetByFilterAsync(filter, _cancellationTokenSource.Token); 62 | 63 | //Assert 64 | Assert.Equal("test1@test.com", result.Email); 65 | } 66 | 67 | [Fact] 68 | public async Task CreateOkTestAsync() 69 | { 70 | await using var connection = await CreateAndOpenSqliteConnectionAsync(); 71 | var options = await SetDbContextOptionsBuilderAsync(connection); 72 | 73 | await using var context = new CustomerContext(options); 74 | Assert.True(await context.Database.EnsureCreatedAsync()); 75 | 76 | //Arrange 77 | var customer = CreateCustomer(); 78 | var repository = new CustomerRepository(context); 79 | repository.Add(customer); 80 | 81 | //Act 82 | var result = await repository.SaveChangesAsync(_cancellationTokenSource.Token); 83 | 84 | //Assert 85 | Assert.Equal(1, result); 86 | } 87 | 88 | [Fact] 89 | public async Task DeleteTestAsync() 90 | { 91 | await using var connection = await CreateAndOpenSqliteConnectionAsync(); 92 | var options = await SetDbContextOptionsBuilderAsync(connection); 93 | 94 | await using var context = new CustomerContext(options); 95 | Assert.True(await context.Database.EnsureCreatedAsync()); 96 | 97 | //Arrange 98 | var newCustomer = CreateCustomer(); 99 | 100 | var repository = new CustomerRepository(context); 101 | repository.Add(newCustomer); 102 | await repository.SaveChangesAsync(_cancellationTokenSource.Token); 103 | 104 | var storedCustomer = await repository.GetByIdAsync(newCustomer.Id, _cancellationTokenSource.Token); 105 | repository.Remove(storedCustomer); 106 | await repository.SaveChangesAsync(_cancellationTokenSource.Token); 107 | 108 | //Act 109 | var nonExistentUser = await repository.GetByIdAsync(newCustomer.Id, _cancellationTokenSource.Token); 110 | 111 | //Assert 112 | Assert.Null(nonExistentUser); 113 | } 114 | 115 | [Fact] 116 | public async Task DuplicatedEmailTestAsync() 117 | { 118 | await using var connection = await CreateAndOpenSqliteConnectionAsync(); 119 | var options = await SetDbContextOptionsBuilderAsync(connection); 120 | 121 | await using var context = new CustomerContext(options); 122 | Assert.True(await context.Database.EnsureCreatedAsync()); 123 | 124 | //Arrange 125 | var customerOne = CreateCustomer(); 126 | var customerTwo = CreateCustomer(); 127 | customerTwo.FirstName = "FirstNameTwo"; 128 | customerTwo.Surname = "Surname Two"; 129 | 130 | var repository = new CustomerRepository(context); 131 | repository.Add(customerOne); 132 | await repository.SaveChangesAsync(_cancellationTokenSource.Token); 133 | 134 | repository.Add(customerTwo); 135 | 136 | //Act & Assert 137 | await Assert.ThrowsAsync(() => repository.SaveChangesAsync(_cancellationTokenSource.Token)); 138 | } 139 | 140 | [Fact] 141 | public async Task CreateInvalidEmailTestAsync() 142 | { 143 | await using var connection = await CreateAndOpenSqliteConnectionAsync(); 144 | var options = await SetDbContextOptionsBuilderAsync(connection); 145 | 146 | await using var context = new CustomerContext(options); 147 | Assert.True(await context.Database.EnsureCreatedAsync()); 148 | 149 | //Arrange 150 | var customer = CreateCustomer(); 151 | customer.Email = null; 152 | 153 | var repository = new CustomerRepository(context); 154 | repository.Add(customer); 155 | 156 | //Act & Assert 157 | await Assert.ThrowsAsync(() => repository.SaveChangesAsync(_cancellationTokenSource.Token)); 158 | } 159 | 160 | [Fact] 161 | public async Task CreateInvalidPasswordTestAsync() 162 | { 163 | await using var connection = await CreateAndOpenSqliteConnectionAsync(); 164 | var options = await SetDbContextOptionsBuilderAsync(connection); 165 | 166 | await using var context = new CustomerContext(options); 167 | Assert.True(await context.Database.EnsureCreatedAsync()); 168 | 169 | //Arrange 170 | var customer = CreateCustomer(); 171 | customer.Password = null; 172 | 173 | var repository = new CustomerRepository(context); 174 | repository.Add(customer); 175 | 176 | //Act & Assert 177 | await Assert.ThrowsAsync(() => repository.SaveChangesAsync(_cancellationTokenSource.Token)); 178 | } 179 | 180 | [Fact] 181 | public async Task CreateInvalidFirstNameTestAsync() 182 | { 183 | await using var connection = await CreateAndOpenSqliteConnectionAsync(); 184 | var options = await SetDbContextOptionsBuilderAsync(connection); 185 | 186 | await using var context = new CustomerContext(options); 187 | Assert.True(await context.Database.EnsureCreatedAsync()); 188 | 189 | //Arrange 190 | var customer = CreateCustomer(); 191 | customer.FirstName = null; 192 | 193 | var repository = new CustomerRepository(context); 194 | repository.Add(customer); 195 | 196 | //Act & Assert 197 | await Assert.ThrowsAsync(() => repository.SaveChangesAsync(_cancellationTokenSource.Token)); 198 | } 199 | 200 | [Fact] 201 | public async Task CreateInvalidSurnameTestAsync() 202 | { 203 | await using var connection = await CreateAndOpenSqliteConnectionAsync(); 204 | var options = await SetDbContextOptionsBuilderAsync(connection); 205 | 206 | await using var context = new CustomerContext(options); 207 | Assert.True(await context.Database.EnsureCreatedAsync()); 208 | 209 | //Arrange 210 | var customer = CreateCustomer(); 211 | customer.Surname = null; 212 | 213 | var repository = new CustomerRepository(context); 214 | repository.Add(customer); 215 | 216 | //Act & Assert 217 | await Assert.ThrowsAsync(() => repository.SaveChangesAsync(_cancellationTokenSource.Token)); 218 | } 219 | 220 | private static Customer.Domain.Entities.Customer CreateCustomer() 221 | { 222 | return new Customer.Domain.Entities.Customer 223 | { 224 | Password = "Password01@", 225 | Email = "test1@test.com", 226 | Surname = "Surname1", 227 | FirstName = "FirstName1", 228 | Updated = DateTime.Now, 229 | Created = DateTime.Now 230 | }; 231 | } 232 | 233 | private static async Task> SetDbContextOptionsBuilderAsync( 234 | DbConnection connection) 235 | { 236 | return await Task.FromResult(new DbContextOptionsBuilder() 237 | .UseSqlite(connection) 238 | .Options); 239 | } 240 | 241 | private static async Task CreateAndOpenSqliteConnectionAsync() 242 | { 243 | var connection = await CreateSqLiteConnectionAsync(); 244 | await connection.OpenAsync(); 245 | return connection; 246 | } 247 | 248 | private static async Task CreateSqLiteConnectionAsync() 249 | { 250 | return await Task.FromResult(new SqliteConnection("DataSource=:memory:")); 251 | } 252 | } -------------------------------------------------------------------------------- /src/CF.Customer.UnitTest/Domain/Services/CustomerServiceTest.cs: -------------------------------------------------------------------------------- 1 | using CF.Customer.Domain.Exceptions; 2 | using CF.Customer.Domain.Models; 3 | using CF.Customer.Domain.Repositories; 4 | using CF.Customer.Domain.Services; 5 | using CF.Customer.Domain.Services.Interfaces; 6 | using Moq; 7 | using Xunit; 8 | 9 | namespace CF.Customer.UnitTest.Domain.Services; 10 | 11 | public class CustomerServiceTest 12 | { 13 | private readonly CancellationTokenSource _cancellationTokenSource = new(); 14 | private readonly Mock _mockPassword = new(); 15 | private readonly Mock _mockRepository = new(); 16 | 17 | [Fact] 18 | public async Task GetByFilterAsync_ReturnsCorrectCustomer() 19 | { 20 | // Arrange 21 | var customer = CreateCustomer(); 22 | 23 | _mockRepository.Setup(x => x.GetByFilterAsync(It.IsAny(), _cancellationTokenSource.Token)) 24 | .ReturnsAsync(customer); 25 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 26 | 27 | // Act 28 | var result = 29 | await customerService.GetByFilterAsync(new CustomerFilter { Id = 1 }, _cancellationTokenSource.Token); 30 | 31 | // Assert 32 | Assert.Equal(customer.Id, result.Id); 33 | } 34 | 35 | [Fact] 36 | public async Task GetListTestAsync() 37 | { 38 | // Arrange 39 | var customerOne = CreateCustomer(); 40 | var customerTwo = CreateCustomer(2, "test2@test.com"); 41 | 42 | var customers = new List 43 | { 44 | customerOne, 45 | customerTwo 46 | }; 47 | 48 | // Act 49 | var filter = new CustomerFilter { PageSize = 10, CurrentPage = 1 }; 50 | _mockRepository.Setup(x => x.CountByFilterAsync(It.IsAny(), _cancellationTokenSource.Token)) 51 | .ReturnsAsync(customers.Count); 52 | _mockRepository.Setup(x => x.GetListByFilterAsync(It.IsAny(), _cancellationTokenSource.Token)) 53 | .ReturnsAsync(customers); 54 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 55 | var result = await customerService.GetListByFilterAsync(filter, _cancellationTokenSource.Token); 56 | 57 | // Assert 58 | Assert.Equal(2, result.Count); 59 | } 60 | 61 | [Theory] 62 | [InlineData(0, "F")] 63 | [InlineData(0, "")] 64 | [InlineData(0, 65 | "First Name First Name First Name First Name First Name First Name First Name First Name First Name First Name First Name.")] 66 | public async Task CreateAsync_InvalidFirstName_ThrowsValidationException(int id, string firstName) 67 | { 68 | // Arrange 69 | var customer = CreateCustomer(id); 70 | customer.FirstName = firstName; 71 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 72 | 73 | // Act & Assert 74 | await Assert.ThrowsAsync(() => 75 | customerService.CreateAsync(customer, _cancellationTokenSource.Token)); 76 | } 77 | 78 | [Theory] 79 | [InlineData("")] 80 | [InlineData("S")] 81 | [InlineData( 82 | "Surname Surname Surname Surname Surname Surname Surname Surname Surname Surname Surname Surname Surname Surname Surname Surname")] 83 | public async Task CreateAsync_InvalidSurname_ThrowsValidationException(string surname) 84 | { 85 | // Arrange 86 | var customer = CreateCustomer(); 87 | customer.Surname = surname; 88 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 89 | 90 | // Act & Assert 91 | await Assert.ThrowsAsync(() => 92 | customerService.CreateAsync(customer, _cancellationTokenSource.Token)); 93 | } 94 | 95 | [Theory] 96 | [InlineData("invalid_email")] 97 | [InlineData("")] 98 | public async Task CreateAsync_InvalidEmail_ThrowsValidationException(string email) 99 | { 100 | // Arrange 101 | var customer = CreateCustomer(); 102 | customer.Email = email; 103 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 104 | 105 | // Act & Assert 106 | await Assert.ThrowsAsync(() => 107 | customerService.CreateAsync(customer, _cancellationTokenSource.Token)); 108 | } 109 | 110 | [Theory] 111 | [InlineData("")] 112 | [InlineData("P@01")] 113 | public async Task CreateAsync_InvalidPassword_ThrowsValidationException(string password) 114 | { 115 | // Arrange 116 | var customer = CreateCustomer(); 117 | customer.Password = password; 118 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 119 | 120 | // Act & Assert 121 | await Assert.ThrowsAsync(() => 122 | customerService.CreateAsync(customer, _cancellationTokenSource.Token)); 123 | } 124 | 125 | [Fact] 126 | public async Task CreateAsync_Success_HashesPassword() 127 | { 128 | // Arrange 129 | var customer = CreateCustomer(); 130 | const string hashedPassword = "$2a$11$hashedPasswordExample"; 131 | 132 | _mockRepository.Setup(x => x.GetByFilterAsync(It.IsAny(), _cancellationTokenSource.Token)) 133 | .ReturnsAsync((Customer.Domain.Entities.Customer)null); 134 | _mockPassword.Setup(x => x.Hash(customer.Password)).Returns(hashedPassword); 135 | _mockRepository.Setup(x => x.SaveChangesAsync(_cancellationTokenSource.Token)).ReturnsAsync(1); 136 | 137 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 138 | 139 | // Act 140 | await customerService.CreateAsync(customer, _cancellationTokenSource.Token); 141 | 142 | // Assert 143 | _mockPassword.Verify(x => x.Hash(It.IsAny()), Times.Once); 144 | Assert.Equal(hashedPassword, customer.Password); 145 | } 146 | 147 | [Fact] 148 | public async Task UpdateAsync_PasswordChanged_HashesNewPassword() 149 | { 150 | // Arrange 151 | var existingCustomer = CreateCustomer(); 152 | const string oldHashedPassword = "$2a$11$oldHashedPassword"; 153 | existingCustomer.Password = oldHashedPassword; 154 | 155 | var updatedCustomer = CreateCustomer(); 156 | const string newPlainPassword = "NewPassword@123"; 157 | updatedCustomer.Password = newPlainPassword; 158 | 159 | const string newHashedPassword = "$2a$11$newHashedPassword"; 160 | 161 | _mockRepository.Setup(x => x.GetByIdAsync(existingCustomer.Id, _cancellationTokenSource.Token)) 162 | .ReturnsAsync(existingCustomer); 163 | _mockRepository.Setup(x => x.GetByFilterAsync(It.IsAny(), _cancellationTokenSource.Token)) 164 | .ReturnsAsync((Customer.Domain.Entities.Customer)null); 165 | _mockPassword.Setup(x => x.Verify(newPlainPassword, oldHashedPassword)).Returns(false); 166 | _mockPassword.Setup(x => x.Hash(newPlainPassword)).Returns(newHashedPassword); 167 | _mockRepository.Setup(x => x.SaveChangesAsync(_cancellationTokenSource.Token)).ReturnsAsync(1); 168 | 169 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 170 | 171 | // Act 172 | await customerService.UpdateAsync(existingCustomer.Id, updatedCustomer, _cancellationTokenSource.Token); 173 | 174 | // Assert 175 | _mockPassword.Verify(x => x.Verify(newPlainPassword, oldHashedPassword), Times.Once); 176 | _mockPassword.Verify(x => x.Hash(newPlainPassword), Times.Once); 177 | Assert.Equal(newHashedPassword, existingCustomer.Password); 178 | } 179 | 180 | [Fact] 181 | public async Task UpdateAsync_PasswordUnchanged_DoesNotHashPassword() 182 | { 183 | // Arrange 184 | var existingCustomer = CreateCustomer(); 185 | existingCustomer.Password = "$2a$11$hashedPassword"; 186 | 187 | var updatedCustomer = CreateCustomer(); 188 | updatedCustomer.Password = "Password@01"; // Original password before hashing 189 | 190 | _mockRepository.Setup(x => x.GetByIdAsync(existingCustomer.Id, _cancellationTokenSource.Token)) 191 | .ReturnsAsync(existingCustomer); 192 | _mockRepository.Setup(x => x.GetByFilterAsync(It.IsAny(), _cancellationTokenSource.Token)) 193 | .ReturnsAsync((Customer.Domain.Entities.Customer)null); 194 | _mockPassword.Setup(x => x.Verify(updatedCustomer.Password, existingCustomer.Password)).Returns(true); 195 | _mockRepository.Setup(x => x.SaveChangesAsync(_cancellationTokenSource.Token)).ReturnsAsync(1); 196 | 197 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 198 | 199 | // Act 200 | await customerService.UpdateAsync(existingCustomer.Id, updatedCustomer, _cancellationTokenSource.Token); 201 | 202 | // Assert 203 | _mockPassword.Verify(x => x.Verify(updatedCustomer.Password, existingCustomer.Password), Times.Once); 204 | _mockPassword.Verify(x => x.Hash(It.IsAny()), Times.Never); 205 | Assert.Equal("$2a$11$hashedPassword", existingCustomer.Password); // Password unchanged 206 | } 207 | 208 | [Fact] 209 | public async Task UpdateInvalidIdTestAsync() 210 | { 211 | // Arrange 212 | var customer = CreateCustomer(0); 213 | 214 | // Act 215 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 216 | 217 | // Act & Assert 218 | await Assert.ThrowsAsync(() => 219 | customerService.UpdateAsync(customer.Id, customer, _cancellationTokenSource.Token)); 220 | } 221 | 222 | [Fact] 223 | public async Task UpdateInvalidCustomerIsNullTestAsync() 224 | { 225 | // Arrange 226 | const long id = 1; 227 | 228 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 229 | 230 | // Act & Assert 231 | await Assert.ThrowsAsync(() => 232 | customerService.UpdateAsync(id, null, _cancellationTokenSource.Token)); 233 | } 234 | 235 | [Fact] 236 | public async Task UpdateInvalidCustomerNotFoundTestAsync() 237 | { 238 | // Arrange 239 | var customer = CreateCustomer(); 240 | 241 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 242 | 243 | // Act & Assert 244 | await Assert.ThrowsAsync(() => 245 | customerService.UpdateAsync(customer.Id, customer, _cancellationTokenSource.Token)); 246 | } 247 | 248 | [Fact] 249 | public async Task DeleteInvalidIdTestAsync() 250 | { 251 | // Arrange 252 | const long id = 0; 253 | 254 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 255 | 256 | // Act & Assert 257 | await Assert.ThrowsAsync(() => 258 | customerService.DeleteAsync(id, _cancellationTokenSource.Token)); 259 | } 260 | 261 | [Fact] 262 | public async Task DeleteAsync_InvalidNotFoundTest_ThrowsValidationException() 263 | { 264 | // Arrange 265 | const long id = 1; 266 | 267 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 268 | 269 | // Act & Assert 270 | await Assert.ThrowsAsync(() => 271 | customerService.DeleteAsync(id, _cancellationTokenSource.Token)); 272 | } 273 | 274 | [Fact] 275 | public async Task IsAvailableEmailTestAsync() 276 | { 277 | // Arrange 278 | var customer = CreateCustomer(); 279 | 280 | _mockRepository.Setup(x => x.GetByFilterAsync(It.IsAny(), _cancellationTokenSource.Token)) 281 | .ReturnsAsync((Customer.Domain.Entities.Customer)null); 282 | 283 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 284 | 285 | // Act 286 | var existingEmail = await customerService.IsAvailableEmailAsync(customer.Email, _cancellationTokenSource.Token); 287 | 288 | // Assert 289 | Assert.True(existingEmail); 290 | } 291 | 292 | [Fact] 293 | public async Task IsNotAvailableEmailTestAsync() 294 | { 295 | // Arrange 296 | var customer = CreateCustomer(); 297 | 298 | var filter = new CustomerFilter { Email = customer.Email }; 299 | _mockRepository.Setup(x => x.GetByFilterAsync(filter, _cancellationTokenSource.Token)) 300 | .ReturnsAsync(customer); 301 | 302 | var customerService = new CustomerService(_mockRepository.Object, _mockPassword.Object); 303 | 304 | // Act 305 | var existingEmail = await customerService.IsAvailableEmailAsync(customer.Email, _cancellationTokenSource.Token); 306 | 307 | // Assert 308 | Assert.True(existingEmail); 309 | } 310 | 311 | private static Customer.Domain.Entities.Customer CreateCustomer(int id = 1, string email = "test1@test.com") 312 | { 313 | return new Customer.Domain.Entities.Customer 314 | { 315 | Id = id, 316 | Password = "Password@01", 317 | Email = email, 318 | Surname = "Surname", 319 | FirstName = "FirstName", 320 | Updated = DateTime.UtcNow, 321 | Created = DateTime.UtcNow 322 | }; 323 | } 324 | } -------------------------------------------------------------------------------- /src/CF.IntegrationTest/CustomerIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Net.Http.Headers; 6 | using System.Threading.Tasks; 7 | using CF.Customer.Application.Dtos; 8 | using CF.IntegrationTest.Factories; 9 | using CF.IntegrationTest.Models; 10 | using Microsoft.AspNetCore.WebUtilities; 11 | using Newtonsoft.Json; 12 | using Newtonsoft.Json.Converters; 13 | using Xunit; 14 | 15 | namespace CF.IntegrationTest; 16 | 17 | public class CustomerIntegrationTest(CustomWebApplicationFactory factory) : IClassFixture 18 | { 19 | private const string CustomerUrl = "api/v1/customer"; 20 | private readonly HttpClient _httpClient = factory.CreateClient(); 21 | 22 | [Fact] 23 | public async Task CreateCustomerOkTestAsync() 24 | { 25 | var dto = CreateCustomerRequestDto(); 26 | var content = await CreateStringContentAsync(dto); 27 | var response = await _httpClient.PostAsync(CustomerUrl, content); 28 | response.EnsureSuccessStatusCode(); 29 | 30 | Assert.Equal(HttpStatusCode.Created, response.StatusCode); 31 | } 32 | 33 | 34 | [Fact] 35 | public async Task CreateCustomerExistingEmailTestAsync() 36 | { 37 | var dto = CreateCustomerRequestDto(); 38 | var content = await CreateStringContentAsync(dto); 39 | var response = await _httpClient.PostAsync(CustomerUrl, content); 40 | Assert.Equal(HttpStatusCode.Created, response.StatusCode); 41 | 42 | content = await CreateStringContentAsync(dto); 43 | var responseNotOk = await _httpClient.PostAsync(CustomerUrl, content); 44 | var errors = await ExtractErrorsFromResponse(responseNotOk); 45 | 46 | Assert.NotNull(errors); 47 | Assert.Contains("Validation", errors); 48 | Assert.Single(errors["Validation"]); 49 | Assert.Equal("Email is not available.", errors["Validation"][0]); 50 | Assert.Equal(HttpStatusCode.BadRequest, responseNotOk.StatusCode); 51 | } 52 | 53 | [Theory] 54 | [InlineData("invalid_email_at_test.com", "The Email field is not a valid email address.")] 55 | [InlineData("", "The Email field is required.")] 56 | [InlineData( 57 | "eeeeeeeeeewedewfdwefweeemmmmmmmmaaaaaaaaaaaaaaiiiiiiiiiiiilllllllllll@teeeeeeesssssssssssssstttttttttttttttt.com", 58 | "The Email field must not exceed 100 characters.")] 59 | public async Task CreateCustomerAsync_Email_Validation_Test(string email, string errorMessage) 60 | { 61 | var dto = CreateCustomerRequestDto(); 62 | dto.Email = email; 63 | 64 | var content = await CreateStringContentAsync(dto); 65 | var response = await _httpClient.PostAsync(CustomerUrl, content); 66 | var errors = await ExtractErrorsFromResponse(response); 67 | 68 | Assert.NotNull(errors); 69 | Assert.Contains("Email", errors); 70 | Assert.NotEmpty(errors["Email"]); 71 | Assert.Equal(errorMessage, errors["Email"][0]); 72 | Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); 73 | } 74 | 75 | [Theory] 76 | [InlineData("", "The First Name field is required.")] 77 | [InlineData( 78 | "Test First Name Test First Name Test First Name Test First Name Test First Name Test First Name Test First Name", 79 | "The First Name field must be between 2 and 100 characters.")] 80 | [InlineData("T", "The First Name field must be between 2 and 100 characters.")] 81 | public async Task CreateCustomerAsync_FirstName_Validation_Test(string firstName, string errorMessage) 82 | { 83 | var dto = CreateCustomerRequestDto(); 84 | dto.FirstName = firstName; 85 | var content = await CreateStringContentAsync(dto); 86 | var response = await _httpClient.PostAsync(CustomerUrl, content); 87 | var errors = await ExtractErrorsFromResponse(response); 88 | 89 | Assert.NotNull(errors); 90 | Assert.Contains("FirstName", errors); 91 | Assert.NotEmpty(errors["FirstName"]); 92 | Assert.Equal(errorMessage, errors["FirstName"][0]); 93 | Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); 94 | } 95 | 96 | [Theory] 97 | [InlineData("", "The Surname field is required.")] 98 | [InlineData( 99 | "Test Surname Test Surname Test Surname Test Surname Test Surname Test Surname Test Surname Test Surname Test Surname", 100 | "The Surname field must be between 2 and 100 characters.")] 101 | [InlineData("T", "The Surname field must be between 2 and 100 characters.")] 102 | public async Task CreateCustomerAsync_Surname_Validation_Test(string surname, string errorMessage) 103 | { 104 | var dto = CreateCustomerRequestDto(); 105 | dto.Surname = surname; 106 | var content = await CreateStringContentAsync(dto); 107 | var response = await _httpClient.PostAsync(CustomerUrl, content); 108 | var errors = await ExtractErrorsFromResponse(response); 109 | 110 | Assert.NotNull(errors); 111 | Assert.Contains("Surname", errors); 112 | Assert.NotEmpty(errors["Surname"]); 113 | Assert.Equal(errorMessage, errors["Surname"][0]); 114 | Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); 115 | } 116 | 117 | [Theory] 118 | [InlineData("", "The Password field is required.")] 119 | [InlineData("@123RF", 120 | "Passwords must be at least 8 characters and contain at least 3 of the following: upper case (A-Z), lower case (a-z), number (0-9), and special character (e.g. !@#$%^&*).")] 121 | [InlineData("01234567901234", 122 | "Passwords must be at least 8 characters and contain at least 3 of the following: upper case (A-Z), lower case (a-z), number (0-9), and special character (e.g. !@#$%^&*).")] 123 | public async Task CreateCustomerAsync_Password_Validation_Test(string password, string errorMessage) 124 | { 125 | var dto = CreateCustomerRequestDto(); 126 | dto.Password = password; 127 | 128 | var content = await CreateStringContentAsync(dto); 129 | var response = await _httpClient.PostAsync(CustomerUrl, content); 130 | var errors = await ExtractErrorsFromResponse(response); 131 | 132 | Assert.NotNull(errors); 133 | Assert.Contains("Password", errors); 134 | Assert.NotEmpty(errors["Password"]); 135 | Assert.Equal(errorMessage, errors["Password"][0]); 136 | Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); 137 | } 138 | 139 | [Fact] 140 | public async Task CreateCustomerAsync_ConfirmPassword_Validation_Test() 141 | { 142 | var dto = CreateCustomerRequestDto(); 143 | dto.ConfirmPassword = "Password3!"; 144 | 145 | var content = await CreateStringContentAsync(dto); 146 | var response = await _httpClient.PostAsync(CustomerUrl, content); 147 | 148 | var errors = await ExtractErrorsFromResponse(response); 149 | 150 | Assert.NotNull(errors); 151 | Assert.Contains("ConfirmPassword", errors); 152 | Assert.NotEmpty(errors["ConfirmPassword"]); 153 | Assert.Equal("The passwords do not match.", errors["ConfirmPassword"][0]); 154 | Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); 155 | } 156 | 157 | [Fact] 158 | public async Task UpdateCustomerOkTestAsync() 159 | { 160 | var dto = CreateCustomerRequestDto(); 161 | 162 | var content = await CreateStringContentAsync(dto); 163 | var createResponse = await _httpClient.PostAsync(CustomerUrl, content); 164 | Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode); 165 | 166 | var getResponse = await _httpClient.GetAsync(createResponse.Headers.Location?.ToString()); 167 | Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); 168 | var customer = 169 | JsonConvert.DeserializeObject(await getResponse.Content.ReadAsStringAsync()); 170 | 171 | dto.FirstName = "New Name"; 172 | var contentUpdate = await CreateStringContentAsync(dto); 173 | var putResponse = await _httpClient.PutAsync($"{CustomerUrl}/{customer.Id}", contentUpdate); 174 | Assert.True(putResponse.IsSuccessStatusCode); 175 | Assert.Equal(HttpStatusCode.NoContent, putResponse.StatusCode); 176 | } 177 | 178 | [Fact] 179 | public async Task UpdateCustomerIncludingPasswordOkTestAsync() 180 | { 181 | var dto = CreateCustomerRequestDto(); 182 | 183 | var content = await CreateStringContentAsync(dto); 184 | var createResponse = await _httpClient.PostAsync(CustomerUrl, content); 185 | Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode); 186 | 187 | var getResponse = await _httpClient.GetAsync(createResponse.Headers.Location?.ToString()); 188 | Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); 189 | var customer = 190 | JsonConvert.DeserializeObject(await getResponse.Content.ReadAsStringAsync()); 191 | 192 | dto.FirstName = "New Name"; 193 | dto.Password = "NewPassword3@"; 194 | dto.ConfirmPassword = "NewPassword3@"; 195 | var contentUpdate = await CreateStringContentAsync(dto); 196 | var putResponse = await _httpClient.PutAsync($"{CustomerUrl}/{customer.Id}", contentUpdate); 197 | Assert.True(putResponse.IsSuccessStatusCode); 198 | Assert.Equal(HttpStatusCode.NoContent, putResponse.StatusCode); 199 | } 200 | 201 | [Fact] 202 | public async Task UpdateCustomerExistingEmailTestAsync() 203 | { 204 | var dto = CreateCustomerRequestDto(); 205 | var customerOneEmail = dto.Email; 206 | 207 | var contentCustomerOne = await CreateStringContentAsync(dto); 208 | var createCustomerOneResponse = await _httpClient.PostAsync(CustomerUrl, contentCustomerOne); 209 | Assert.Equal(HttpStatusCode.Created, createCustomerOneResponse.StatusCode); 210 | 211 | dto.Email = $"new_{customerOneEmail}"; 212 | 213 | var contentCustomerTwo = await CreateStringContentAsync(dto); 214 | var createCustomerTwoResponse = await _httpClient.PostAsync(CustomerUrl, contentCustomerTwo); 215 | Assert.Equal(HttpStatusCode.Created, createCustomerTwoResponse.StatusCode); 216 | 217 | var parameters = new Dictionary { { "email", dto.Email } }; 218 | var requestUri = QueryHelpers.AddQueryString(CustomerUrl, parameters); 219 | var getResponse = await _httpClient.GetAsync(requestUri); 220 | Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); 221 | var customer = 222 | JsonConvert.DeserializeObject(await getResponse.Content.ReadAsStringAsync()); 223 | 224 | dto.Email = customerOneEmail; 225 | var content = await CreateStringContentAsync(dto); 226 | var response = await _httpClient.PutAsync($"{CustomerUrl}/{customer.Id}", content); 227 | 228 | var errors = await ExtractErrorsFromResponse(response); 229 | 230 | Assert.NotNull(errors); 231 | Assert.Contains("Id", errors); 232 | Assert.NotEmpty(errors["Id"]); 233 | Assert.Equal("Invalid Id.", errors["Id"][0]); 234 | Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); 235 | } 236 | 237 | [Fact] 238 | public async Task GetCustomerTestAsync() 239 | { 240 | var dto = CreateCustomerRequestDto(); 241 | 242 | var content = await CreateStringContentAsync(dto); 243 | var response = await _httpClient.PostAsync(CustomerUrl, content); 244 | Assert.Equal(HttpStatusCode.Created, response.StatusCode); 245 | 246 | var getResponse = await _httpClient.GetAsync(response.Headers.Location?.ToString()); 247 | Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); 248 | } 249 | 250 | [Fact] 251 | public async Task GetCustomerInvalidIdValueTestAsync() 252 | { 253 | var response = await _httpClient.GetAsync($"{CustomerUrl}/l"); 254 | 255 | // With {id:long} route constraint, invalid values return 404 instead of reaching controller 256 | Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); 257 | } 258 | 259 | [Fact] 260 | public async Task GetCustomerInvalidIdNegativeTestAsync() 261 | { 262 | var response = await _httpClient.GetAsync($"{CustomerUrl}/-1"); 263 | var errors = await ExtractErrorsFromResponse(response); 264 | 265 | Assert.NotNull(errors); 266 | Assert.Contains("Id", errors); 267 | Assert.NotEmpty(errors["Id"]); 268 | Assert.Equal("Invalid Id.", errors["Id"][0]); 269 | Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); 270 | } 271 | 272 | [Fact] 273 | public async Task GetCustomerListTestAsync() 274 | { 275 | var dto = CreateCustomerRequestDto(); 276 | var content = await CreateStringContentAsync(dto); 277 | var response = await _httpClient.PostAsync(CustomerUrl, content); 278 | Assert.Equal(HttpStatusCode.Created, response.StatusCode); 279 | 280 | dto.Email = $"new_{dto.Email}"; 281 | var contentTwo = await CreateStringContentAsync(dto); 282 | var responseTwo = await _httpClient.PostAsync(CustomerUrl, contentTwo); 283 | Assert.Equal(HttpStatusCode.Created, responseTwo.StatusCode); 284 | 285 | var parameters = new Dictionary 286 | { 287 | { "currentPage", "1" }, 288 | { "pageSize", "1" }, 289 | { "orderBy", dto.FirstName }, 290 | { "sortBy", "asc" } 291 | }; 292 | 293 | var requestUri = QueryHelpers.AddQueryString(CustomerUrl, parameters); 294 | 295 | var getResponse = await _httpClient.GetAsync(requestUri); 296 | Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); 297 | var customers = 298 | JsonConvert.DeserializeObject>( 299 | await getResponse.Content.ReadAsStringAsync()); 300 | Assert.True(customers.Count > 1); 301 | Assert.NotEmpty(customers.Result); 302 | } 303 | 304 | [Fact] 305 | public async Task DeleteCustomerOkTestAsync() 306 | { 307 | var dto = CreateCustomerRequestDto(); 308 | 309 | var content = await CreateStringContentAsync(dto); 310 | 311 | var response = await _httpClient.PostAsync(CustomerUrl, content); 312 | Assert.Equal(HttpStatusCode.Created, response.StatusCode); 313 | 314 | var getResponse = await _httpClient.GetAsync(response.Headers.Location?.ToString()); 315 | Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode); 316 | var customer = 317 | JsonConvert.DeserializeObject(await getResponse.Content.ReadAsStringAsync()); 318 | 319 | var deleteResponse = await _httpClient.DeleteAsync($"{CustomerUrl}/{customer.Id}"); 320 | Assert.Equal(HttpStatusCode.NoContent, deleteResponse.StatusCode); 321 | } 322 | 323 | private static async Task CreateStringContentAsync(CustomerRequestDto dto) 324 | { 325 | var content = await Task.FromResult(new StringContent(JsonConvert.SerializeObject(dto))); 326 | content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 327 | return content; 328 | } 329 | 330 | private static CustomerRequestDto CreateCustomerRequestDto() 331 | { 332 | return new CustomerRequestDto 333 | { 334 | FirstName = "Test Name", 335 | Surname = "Test Surname", 336 | Email = $"{DateTime.Now:yyyyMMdd_hhmmssfff}@test.com", 337 | Password = "Password1@", 338 | ConfirmPassword = "Password1@" 339 | }; 340 | } 341 | 342 | private static async Task> ExtractErrorsFromResponse(HttpResponseMessage response) 343 | { 344 | var responseContent = 345 | JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync(), 346 | new ExpandoObjectConverter()); 347 | var errors = 348 | (IDictionary)JsonConvert.DeserializeObject>( 349 | responseContent.Errors.ToString()); 350 | return errors; 351 | } 352 | } --------------------------------------------------------------------------------