Skip to content

Commit

Permalink
Merge pull request #19 from DFE-Digital/task/190887-project-integrati…
Browse files Browse the repository at this point in the history
…on-tests

task/190887-project-integration-tests
  • Loading branch information
sukhybhullar-nimble authored Dec 17, 2024
2 parents 25cfcbd + 54e1327 commit 110f1a1
Show file tree
Hide file tree
Showing 15 changed files with 151 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<Title>API Client</Title>
<Description>The API description.</Description>
<Authors>DFE-Digital</Authors>
<UserSecretsId>9d380f80-743c-4d55-bfb8-0b7b366bb5ab</UserSecretsId>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ public static IServiceCollection AddCompleteApiClient<TClientInterface, TClientI
where TClientInterface : class
where TClientImplementation : class, TClientInterface
{
var apiSettings = new ApiClientSettings();
var apiSettings = new ApiClientSettings();

configuration.GetSection("CompleteApiClient").Bind(apiSettings);

services.AddSingleton(apiSettings);
Expand Down Expand Up @@ -46,6 +47,7 @@ public static IServiceCollection AddCompleteApiClient<TClientInterface, TClientI
return new BearerTokenHandler(tokenService);
});
}

return services;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Api/Dfe.Complete.Api/Controllers/SchoolsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public async Task<IActionResult> GetPrincipalsBySchoolsAsync([FromBody] GetPrinc
/// </summary>
/// <param name="request">The request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
[Authorize(Policy = "API.Write")]
// [Authorize(Policy = "API.Write")]
[HttpPost]
[SwaggerResponse(201, "School created successfully.", typeof(SchoolId))]
[SwaggerResponse(400, "Invalid request data.")]
Expand Down
3 changes: 1 addition & 2 deletions src/Api/Dfe.Complete.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ public class Program
{
public static async Task Main(string[] args)
{

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((context, services, loggerConfiguration) =>
{
loggerConfiguration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ public record CreateConversionProjectCommand(
string AdvisoryBoardConditions,
string EstablishmentSharepointLink,
string IncomingTrustSharepointLink) : IRequest<ProjectId>;



public class CreateConversionProjectCommandHandler(ICompleteRepository<Project> projectRepository, ICompleteRepository<ConversionTasksData> conversionTaskRepository)
: IRequestHandler<CreateConversionProjectCommand, ProjectId>
{
Expand All @@ -46,7 +45,7 @@ public async Task<ProjectId> Handle(CreateConversionProjectCommand request, Canc
request.AdvisoryBoardConditions,
request.EstablishmentSharepointLink,
request.IncomingTrustSharepointLink);

await conversionTaskRepository.AddAsync(conversionTask, cancellationToken);
await projectRepository.AddAsync(project, cancellationToken);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,7 @@ public record CreateSchoolCommand(
PrincipalDetailsModel PrincipalDetails
) : IRequest<SchoolId>;

public class CreateSchoolCommandHandler(ISclRepository<School> schoolRepository)
: IRequestHandler<CreateSchoolCommand, SchoolId>
public class CreateSchoolCommandHandler(ISclRepository<School> schoolRepository) : IRequestHandler<CreateSchoolCommand, SchoolId>
{
public async Task<SchoolId> Handle(CreateSchoolCommand request, CancellationToken cancellationToken)
{
Expand Down
40 changes: 20 additions & 20 deletions src/Core/Dfe.Complete.Domain/Entities/Project.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ public class Project : BaseAggregateRoot, IEntity<ProjectId>

public virtual User? RegionalDeliveryOfficer { get; set; }

private Project() { }
private Project()
{
}

public Project(
Urn urn,
Expand All @@ -111,7 +113,7 @@ public Project(
string advisoryBoardConditions,
string establishmentSharepointLink,
string incomingTrustSharepointLink
)
)
{
Urn = urn ?? throw new ArgumentNullException(nameof(urn));
CreatedAt = createdAt != default ? createdAt : throw new ArgumentNullException(nameof(createdAt));
Expand Down Expand Up @@ -150,27 +152,25 @@ public static Project Create(Urn urn,
string incomingTrustSharepointLink)
{
var project = new Project(urn,
createdAt,
updatedAt,
taskType,
projectType,
tasksDataId,
significantDate,
isSignificantDateProvisional,
incomingTrustUkprn,
region,
isDueTo2RI,
hasAcademyOrderBeenIssued,
advisoryBoardDate,
advisoryBoardConditions,
establishmentSharepointLink,
incomingTrustSharepointLink);
createdAt,
updatedAt,
taskType,
projectType,
tasksDataId,
significantDate,
isSignificantDateProvisional,
incomingTrustUkprn,
region,
isDueTo2RI,
hasAcademyOrderBeenIssued,
advisoryBoardDate,
advisoryBoardConditions,
establishmentSharepointLink,
incomingTrustSharepointLink);

project.AddDomainEvent(new ProjectCreatedEvent(project));


return project;
}


}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ public CompleteContext(DbContextOptions<CompleteContext> options, IConfiguration
_configuration = configuration;
_serviceProvider = serviceProvider;
}



public virtual DbSet<Contact> Contacts { get; set; }

public virtual DbSet<ConversionTasksData> ConversionTasksData { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,13 @@ public static IServiceCollection AddInfrastructureDependencyGroup(
//Db
var connectionString = config.GetConnectionString("DefaultConnection");

services.AddDbContext<SclContext>(options =>
options.UseSqlServer(connectionString));

services.AddDbContext<CompleteContext>(options =>
options.UseSqlServer(connectionString));
services.AddDbContext<SclContext>(options => options.UseSqlServer(connectionString));
services.AddDbContext<CompleteContext>(options => options.UseSqlServer(connectionString));

// Authentication
//services.AddCustomAuthorization(config);

return services;
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Microsoft.Extensions.DependencyInjection.Projects.EventHandlers;

public class ProjectCreatedEventHandler
{

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Net;
using Dfe.Complete.Client.Contracts;
using Dfe.Complete.Tests.Common.Customizations;
using Dfe.Complete.Tests.Common.Customizations.Commands;
using DfE.CoreLibs.Testing.AutoFixture.Attributes;
using DfE.CoreLibs.Testing.Mocks.WebApplicationFactory;

namespace Dfe.Complete.Api.Tests.Integration.Controllers;

public class ProjectsControllerTests
{
[Theory]
[CustomAutoData(typeof(CustomWebApplicationDbContextFactoryCustomization),
typeof(CreateConversionProjectCommandCustomization))]
public async Task CreateProject_Async_ShouldCreateConversionProject(
CustomWebApplicationDbContextFactory<Program> factory,
CreateConversionProjectCommand createConversionProjectCommand,
ICreateProjectClient createProjectClient)
{
//todo: when auth is done, add this back in
// factory.TestClaims = [new Claim(ClaimTypes.Role, "API.Write")];

var result = await createProjectClient.Projects_CreateProject_Async(createConversionProjectCommand);

Assert.NotNull(result);
Assert.IsType<ProjectId>(result);
}

[Theory]
[CustomAutoData(typeof(CustomWebApplicationDbContextFactoryCustomization))]
public async Task CreateProject_WithNullRequest_ThrowsException(
CustomWebApplicationDbContextFactory<Program> factory,
CreateConversionProjectCommand createConversionProjectCommand,
ICreateProjectClient createProjectClient)
{
//todo: when auth is done, add this back in
// factory.TestClaims = [new Claim(ClaimTypes.Role, "API.Write")];

createConversionProjectCommand.Urn = null;


//todo: change exception type?
var exception = await Assert.ThrowsAsync<PersonsApiException>(async () =>
await createProjectClient.Projects_CreateProject_Async(createConversionProjectCommand));

Assert.Equal(HttpStatusCode.BadRequest, (HttpStatusCode)exception.StatusCode);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using AutoFixture;
using Dfe.Complete.Application.Projects.Commands.CreateProject;
using Dfe.Complete.Domain.ValueObjects;
using Dfe.Complete.Domain.Enums;

namespace Dfe.Complete.Tests.Common.Customizations.Commands
{
public class CreateConversionProjectCommandCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<CreateConversionProjectCommand>(composer => composer.FromFactory(() =>
{
var urn = new Urn(fixture.Create<int>());
var significantDate = fixture.Create<DateOnly>();
var isSignificantDateProvisional = fixture.Create<bool>();
var incomingTrustUkprn = new Ukprn(fixture.Create<int>());
var region = fixture.Create<Region>();
var isDueTo2Ri = fixture.Create<bool>();
var hasAcademyOrderBeenIssued = fixture.Create<bool>();
var advisoryBoardDate = fixture.Create<DateOnly>();
var advisoryBoardConditions = fixture.Create<string>();
var establishmentSharepointLink = fixture.Create<Uri>().ToString();
var incomingTrustSharepointLink = fixture.Create<Uri>().ToString();

return new CreateConversionProjectCommand(
urn,
significantDate,
isSignificantDateProvisional,
incomingTrustUkprn,
region,
isDueTo2Ri,
hasAcademyOrderBeenIssued,
advisoryBoardDate,
advisoryBoardConditions,
establishmentSharepointLink,
incomingTrustSharepointLink
);
}));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
using Dfe.Complete.Api.Client.Extensions;
using Dfe.Complete.Client;
using Dfe.Complete.Client.Contracts;
using Dfe.Complete.Infrastructure.Database;
using Dfe.Complete.Tests.Common.Seeders;
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Net.Http.Headers;
using System.Security.Claims;
using Dfe.Complete.Infrastructure.Database;
using Dfe.Complete.Tests.Common.Seeders;
using Microsoft.EntityFrameworkCore;

namespace Dfe.Complete.Tests.Common.Customizations
{
Expand All @@ -22,12 +22,14 @@ public void Customize(IFixture fixture)
{
fixture.Customize<CustomWebApplicationDbContextFactory<Program>>(composer => composer.FromFactory(() =>
{

var factory = new CustomWebApplicationDbContextFactory<Program>()
{
//TODO: when needed, seed data for CompleteContext
SeedData = new Dictionary<Type, Action<DbContext>>
{
{ typeof(SclContext), context => SclContextSeeder.Seed((SclContext)context) },
//TODO: add this but for CompleteContext when needed:
//typeof(CompleteContext), context => CompleteContextSeeder.Seed((CompleteContext)context)
{ typeof(CompleteContext), context => {} },
},
ExternalServicesConfiguration = services =>
{
Expand All @@ -51,20 +53,22 @@ public void Customize(IFixture fixture)
var config = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?>
{
{ "ApiClient:BaseUrl", client.BaseAddress!.ToString() }
{ "CompleteApiClient:BaseUrl", client.BaseAddress!.ToString() }
})
.Build();

var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(config);
services.AddCompleteApiClient<ISchoolsClient, SchoolsClient>(config, client);


services.AddCompleteApiClient<ICreateProjectClient, CreateProjectClient>(config, client);

var serviceProvider = services.BuildServiceProvider();

fixture.Inject(factory);
fixture.Inject(serviceProvider);
fixture.Inject(client);
fixture.Inject(serviceProvider.GetRequiredService<ISchoolsClient>());
fixture.Inject(serviceProvider.GetRequiredService<ICreateProjectClient>());

fixture.Inject(new List<Claim>());

return factory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ public void Customize(IFixture fixture)
{
fixture.Customize<CustomWebApplicationFactory<TProgram>>(composer => composer.FromFactory(() =>
{

var factory = new CustomWebApplicationFactory<TProgram>()
{
ExternalServicesConfiguration = services =>
Expand All @@ -31,12 +30,11 @@ public void Customize(IFixture fixture)
});

services.AddAuthentication("TestScheme")
.AddScheme<AuthenticationSchemeOptions, MockJwtBearerHandler>("TestScheme", options => { });
.AddScheme<AuthenticationSchemeOptions, MockJwtBearerHandler>("TestScheme", _ => { });
},
ExternalHttpClientConfiguration = client =>
{
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", "external-mock-token");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "external-mock-token");
}
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Dfe.Complete.Tests.Common.Seeders;

public class CompleteContextSeeder
{
//TODO: implement when needed
}

0 comments on commit 110f1a1

Please sign in to comment.