Skip to content

Commit

Permalink
Merge pull request #442 from DFE-Digital/feature/152055-get-projects-…
Browse files Browse the repository at this point in the history
…from-mfsp

152055: added support for calling external mfsp api to get projects
  • Loading branch information
mikestock-nimble authored Jan 12, 2024
2 parents e62af2b + 1c7fc60 commit 4ade318
Show file tree
Hide file tree
Showing 16 changed files with 264 additions and 131 deletions.
57 changes: 0 additions & 57 deletions TramsDataApi.Test/Controllers/FssProjectControllerTests.cs

This file was deleted.

57 changes: 57 additions & 0 deletions TramsDataApi.Test/FakeApi/FakeMfspApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using FluentValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using TramsDataApi.ResponseModels;

namespace TramsDataApi.Test.FakeApi
{
public class FakeMfspApi
{
private IWebHost _server;

public void Start()
{
_server = new WebHostBuilder().UseKestrel(x => x.ListenLocalhost(5003)).Configure(app =>
{
app.Run(async context =>
{
if (context.Request.Method == HttpMethods.Get && context.Request.Path == "/v2/fss/projects")
{
var response = new List<FssProjectResponse>()
{
new FssProjectResponse()
{
CurrentFreeSchoolName = "This is my free school",
AgeRange = "5-11",
ProjectStatus = "Open",
},
new FssProjectResponse()
{
CurrentFreeSchoolName = "This is another free school",
AgeRange = "11-16",
ProjectStatus = "Open",
},
};

await context.Response.WriteAsJsonAsync(response);
}
else
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
await context.Response.WriteAsync("Not found");
}
});
}).Build();

_server.Start();
}

public void Stop()
{
_server.StopAsync().Wait();
}
}
}
8 changes: 8 additions & 0 deletions TramsDataApi.Test/Fixtures/ApiTestFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using System.IO;
using System.Net.Http;
using System.Net.Mime;
using TramsDataApi.Test.FakeApi;
using Xunit;

namespace TramsDataApi.Test.Fixtures
Expand All @@ -27,6 +28,8 @@ public class ApiTestFixture : IDisposable

private const string ConnectionStringKey = "ConnectionStrings:DefaultConnection";

private FakeMfspApi _fakeMfspApi;

public ApiTestFixture()
{
lock (_lock)
Expand Down Expand Up @@ -63,6 +66,10 @@ public ApiTestFixture()
using var context = GetMstrContext();
context.Database.EnsureDeleted();
context.Database.Migrate();

_fakeMfspApi = new FakeMfspApi();
_fakeMfspApi.Start();

_isInitialised = true;
}
}
Expand All @@ -72,6 +79,7 @@ public void Dispose()
{
_application.Dispose();
Client.Dispose();
_fakeMfspApi.Stop();
}

public MstrContext GetMstrContext() => new MstrContext(_dbContextOptions);
Expand Down
48 changes: 48 additions & 0 deletions TramsDataApi.Test/Integration/FssProjectIntegrationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using FluentAssertions;
using Newtonsoft.Json;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using TramsDataApi.ResponseModels;
using TramsDataApi.Test.Fixtures;
using Xunit;

namespace TramsDataApi.Test.Integration
{
[Collection(ApiTestCollection.ApiTestCollectionName)]
public class FssProjectIntegrationTests
{
private readonly HttpClient _client;

public FssProjectIntegrationTests(ApiTestFixture fixture)
{
_client = fixture.Client;
}

[Fact]
public async Task GetFssProject()
{
var response = await _client.GetAsync($"v2/fss/projects");
response.StatusCode.Should().Be(HttpStatusCode.OK);

var responseContent = await response.Content.ReadAsStringAsync();

var fssProjectsResponse = JsonConvert.DeserializeObject<ApiResponseV2<FssProjectResponse>>(responseContent);

var fssProjects = fssProjectsResponse.Data;

fssProjects.Should().HaveCount(2);

var firstProject = fssProjects.ElementAt(0);
firstProject.CurrentFreeSchoolName.Should().Be("This is my free school");
firstProject.AgeRange.Should().Be("5-11");
firstProject.ProjectStatus.Should().Be("Open");

var secondProject = fssProjects.ElementAt(1);
secondProject.CurrentFreeSchoolName.Should().Be("This is another free school");
secondProject.AgeRange.Should().Be("11-16");
secondProject.ProjectStatus.Should().Be("Open");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ public static IEnumerable<object[]> GetSearchTrustTestSet()
var secondValue = _autoFixture.Create<string>();

yield return new object[] { firstValue, firstValue };
yield return new object[] { secondValue, secondValue.Substring(0, 4) };
yield return new object[] { secondValue, secondValue.Substring(0, 12) };
}
}
}
51 changes: 0 additions & 51 deletions TramsDataApi.Test/UseCases/GetAllFssProjectTests.cs

This file was deleted.

14 changes: 10 additions & 4 deletions TramsDataApi.Test/integration_settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@
}
},
"AllowedHosts": "*",
"ApiKeys": ["{\"userName\": \"Test User\", \"apiKey\": \"testing-api-key\"}"],
"ConnectionStrings": {
"DefaultConnection": "Server=127.0.0.1,1433;Database=sip;User Id=sa;TrustServerCertificate=True;Password=StrongPassword905"
}
"ApiKeys": [ "{\"userName\": \"Test User\", \"apiKey\": \"testing-api-key\"}" ],
"ConnectionStrings": {
"DefaultConnection": "Server=127.0.0.1,1433;Database=sip;User Id=sa;TrustServerCertificate=True;Password=StrongPassword905"
},
"Mfsp": {
"ApiEndpoint": "http://localhost:5003"
},
"FeatureManagement": {
"IsGetProjectsFromMfspEnabled": true
}
}
7 changes: 7 additions & 0 deletions TramsDataApi/Configuration/MfspOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace TramsDataApi.Configuration
{
public class MfspOptions
{
public string ApiEndpoint { get; set; }
}
}
11 changes: 5 additions & 6 deletions TramsDataApi/Controllers/V2/FSSProjectController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using TramsDataApi.ResponseModels;
using TramsDataApi.UseCases;

Expand All @@ -23,17 +24,15 @@ public FssProjectController(ILogger<FssProjectController> logger, IGetAllFssProj

[HttpGet("projects")]
[MapToApiVersion("2.0")]
public ActionResult<ApiResponseV2<FssProjectResponse>> GetAll()
public async Task<ActionResult<ApiResponseV2<FssProjectResponse>>> GetAll()
{
_logger.LogInformation($"Retreiving all FSS Projects ");

var projects = _getAllFssProjects.Execute().ToList();
var projects = await _getAllFssProjects.Execute();

_logger.LogInformation($"Found {0} projects, " , projects.Count);
_logger.LogInformation("Found {0} projects, ", projects.Count);

_logger.LogDebug(JsonSerializer.Serialize(projects));

var response = new ApiResponseV2<FssProjectResponse>(projects.ToList(), null);
var response = new ApiResponseV2<FssProjectResponse>(projects, null);
return new OkObjectResult(response);
}
}
Expand Down
54 changes: 54 additions & 0 deletions TramsDataApi/Services/ApiClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace TramsDataApi.Services
{
public abstract class ApiClient
{
private readonly IHttpClientFactory _clientFactory;
private readonly ILogger<ApiClient> _logger;
private string _httpClientName;

protected ApiClient(IHttpClientFactory clientFactory, ILogger<ApiClient> logger, string httpClientName)
{
_clientFactory = clientFactory;
_logger = logger;
_httpClientName = httpClientName;
}

public async Task<T> Get<T>(string endpoint) where T : class
{
try
{
var request = new HttpRequestMessage(HttpMethod.Get, endpoint);

var client = CreateHttpClient();

var response = await client.SendAsync(request);

response.EnsureSuccessStatusCode();

var content = await response.Content.ReadAsStringAsync();

var result = JsonConvert.DeserializeObject<T>(content);

return result;
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
throw;
}
}

private HttpClient CreateHttpClient()
{
var client = _clientFactory.CreateClient(_httpClientName);

return client;
}
}
}
13 changes: 13 additions & 0 deletions TramsDataApi/Services/MfspApiClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.Extensions.Logging;
using System.Net.Http;

namespace TramsDataApi.Services
{
public class MfspApiClient : ApiClient
{
public MfspApiClient(IHttpClientFactory clientFactory, ILogger<ApiClient> logger, string httpClientName = "MfspApiClient") : base(clientFactory, logger, httpClientName)
{

}
}
}
Loading

0 comments on commit 4ade318

Please sign in to comment.