Skip to content

Commit

Permalink
merged from main branch
Browse files Browse the repository at this point in the history
  • Loading branch information
dpatel017 committed Oct 18, 2024
2 parents f0bf967 + a13254b commit 438ef18
Show file tree
Hide file tree
Showing 75 changed files with 3,945 additions and 128 deletions.
6 changes: 6 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ COPY --link Services/CO.CDP.Organisation.Authority/CO.CDP.Organisation.Authority
COPY --link Services/CO.CDP.Organisation.Authority.Tests/CO.CDP.Organisation.Authority.Tests.csproj Services/CO.CDP.Organisation.Authority.Tests/
COPY --link Services/CO.CDP.EntityVerification/CO.CDP.EntityVerification.csproj Services/CO.CDP.EntityVerification/
COPY --link Services/CO.CDP.EntityVerification.Tests/CO.CDP.EntityVerification.Tests.csproj Services/CO.CDP.EntityVerification.Tests/
COPY --link Services/CO.CDP.Localization/CO.CDP.Localization.csproj Services/CO.CDP.Localization/
COPY --link GCGS-Central-Digital-Platform.sln .
RUN dotnet restore "GCGS-Central-Digital-Platform.sln"

Expand Down Expand Up @@ -107,6 +108,11 @@ ARG BUILD_CONFIGURATION
WORKDIR /src/Services/CO.CDP.Person.WebApi
RUN dotnet build -c $BUILD_CONFIGURATION -o /app/build

FROM build AS build-localization
ARG BUILD_CONFIGURATION
WORKDIR /src/Services/CO.CDP.Localization
RUN dotnet build -c $BUILD_CONFIGURATION -o /app/build

FROM build AS build-forms
ARG BUILD_CONFIGURATION
WORKDIR /src/Services/CO.CDP.Forms.WebApi
Expand Down
170 changes: 170 additions & 0 deletions Frontend/CO.CDP.OrganisationApp.Tests/LocalizationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
using CO.CDP.Organisation.WebApiClient;
using CO.CDP.OrganisationApp.Constants;
using CO.CDP.OrganisationApp.Models;
using CO.CDP.OrganisationApp.ThirdPartyApiClients.CompaniesHouse;
using CO.CDP.Person.WebApiClient;
using CO.CDP.Tenant.WebApiClient;
using FluentAssertions;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using System.Net;
using System.Text.RegularExpressions;

namespace CO.CDP.OrganisationApp.Tests;
public class LocalizationTests
{
public HttpClient BuildHttpClient()
{
Mock<ISession> _mockSession = new Mock<ISession>();
Guid personId = new Guid("5b0d3aa8-94cd-4ede-ba03-546937035690");
var services = new ServiceCollection();

var person = new Person.WebApiClient.Person("[email protected]", "First name", personId, "Last name", null);

_mockSession
.Setup(s => s.Get<Models.UserDetails>(Session.UserDetailsKey))
.Returns(new Models.UserDetails() { Email = "[email protected]", UserUrn = "urn", PersonId = person.Id });

_mockSession
.Setup(s => s.Get<Models.RegistrationDetails>(Session.RegistrationDetailsKey))
.Returns(new Models.RegistrationDetails() { OrganisationType = OrganisationType.Supplier, OrganisationScheme = "Whatever" });

services.AddSingleton(_mockSession.Object);

var antiforgeryMock = new Mock<IAntiforgery>();

antiforgeryMock.Setup(a => a.ValidateRequestAsync(It.IsAny<HttpContext>()))
.Returns(Task.CompletedTask);

antiforgeryMock.Setup(a => a.GetAndStoreTokens(It.IsAny<HttpContext>()))
.Returns(new AntiforgeryTokenSet(
"fakeRequestToken",
"fakeCookieToken",
"fakeFormFieldName",
"fakeHeaderName"));

services.AddSingleton(antiforgeryMock.Object);

services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddScheme<AuthenticationSchemeOptions, FakeCookieAuthHandler>(CookieAuthenticationDefaults.AuthenticationScheme, options => { });

services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options => {
options.ClientId = "123";
options.Authority = "https://whatever";
});

var factory = new CustomisableWebApplicationFactory<Program>(services);

return factory.CreateClient();
}

[Fact]
public async Task OrganisationNamePage_DisplaysCorrectly_WhenLanguageIsDefaulted()
{
var _httpClient = BuildHttpClient();

var request = new HttpRequestMessage(HttpMethod.Get, "/registration/organisation-name");

var response = await _httpClient.SendAsync(request);

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

responseBody.Should().NotBeNull();
response.StatusCode.Should().Be(HttpStatusCode.OK);

responseBody.Should().Contain("Enter the organisation&#x27;s name");
}

[Fact]
public async Task OrganisationNamePage_DisplaysCorrectly_WhenLanguageIsEnglish()
{
var _httpClient = BuildHttpClient();

var request = new HttpRequestMessage(HttpMethod.Get, "/registration/organisation-name");

var cultureCookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture("en"));
request.Headers.Add("Cookie", $"{CookieRequestCultureProvider.DefaultCookieName}={cultureCookieValue}");

var response = await _httpClient.SendAsync(request);

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

responseBody.Should().NotBeNull();
response.StatusCode.Should().Be(HttpStatusCode.OK);

responseBody.Should().Contain("Enter the organisation&#x27;s name");
}

[Fact]
public async Task OrganisationNamePage_DisplaysCorrectly_WhenLanguageIsWelsh()
{
var _httpClient = BuildHttpClient();

var request = new HttpRequestMessage(HttpMethod.Get, "/registration/organisation-name");

var cultureCookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture("cy"));
request.Headers.Add("Cookie", $"{CookieRequestCultureProvider.DefaultCookieName}={cultureCookieValue}");

var response = await _httpClient.SendAsync(request);

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

responseBody.Should().NotBeNull();
response.StatusCode.Should().Be(HttpStatusCode.OK);

responseBody.Should().Contain("Rhowch enw&#x2019;r sefydliad");
}

[Fact]
public async Task OrganisationNamePage_DisplaysErrorMessageCorrectly_WhenLanguageIsEnglish()
{
var _httpClient = BuildHttpClient();

var request = new HttpRequestMessage(HttpMethod.Post, "/registration/organisation-name")
{
Content = new FormUrlEncodedContent(new Dictionary<string, string> { { "OrganisationName", "" } })
};

var response = await _httpClient.SendAsync(request);

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

responseBody.Should().NotBeNull();
response.StatusCode.Should().Be(HttpStatusCode.OK);

responseBody.Should().Contain("<span class=\"field-validation-error\" data-valmsg-for=\"OrganisationName\" data-valmsg-replace=\"true\">Enter the organisation&#x27;s name</span>");
}

[Fact]
public async Task OrganisationNamePage_DisplaysErrorMessageCorrectly_WhenLanguageIsWelsh()
{
var _httpClient = BuildHttpClient();

var request = new HttpRequestMessage(HttpMethod.Post, "/registration/organisation-name")
{
Content = new FormUrlEncodedContent(new Dictionary<string, string> { { "OrganisationName", "" } })
};

var cultureCookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture("cy"));
request.Headers.Add("Cookie", $"{CookieRequestCultureProvider.DefaultCookieName}={cultureCookieValue}");

var response = await _httpClient.SendAsync(request);

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

responseBody.Should().NotBeNull();
response.StatusCode.Should().Be(HttpStatusCode.OK);

responseBody.Should().Contain("<span class=\"field-validation-error\" data-valmsg-for=\"OrganisationName\" data-valmsg-replace=\"true\">Rhowch enw&#x2019;r sefydliad</span>");
}
}
93 changes: 93 additions & 0 deletions Frontend/CO.CDP.OrganisationApp.Tests/Pages/ChangeLanguageTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using CO.CDP.OrganisationApp.Pages;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Moq;

namespace CO.CDP.OrganisationApp.Tests.Pages;

public class ChangeLanguageTests
{
private readonly ChangeLanguageModel _model;
private readonly Mock<ITempDataService> _mockTempDataService;
private readonly Mock<HttpContext> _mockHttpContext;
private readonly Mock<HttpResponse> _mockResponse;
private readonly Mock<HttpRequest> _mockRequest;
private readonly Mock<IResponseCookies> _mockCookies;
private readonly Mock<IUrlHelper> _mockUrlHelper;

public ChangeLanguageTests()
{
_mockTempDataService = new Mock<ITempDataService>();
_model = new ChangeLanguageModel(_mockTempDataService.Object);
_mockHttpContext = new Mock<HttpContext>();
_mockResponse = new Mock<HttpResponse>();
_mockRequest = new Mock<HttpRequest>();
_mockCookies = new Mock<IResponseCookies>();
_mockUrlHelper = new Mock<IUrlHelper>();

_mockResponse.Setup(r => r.Cookies).Returns(_mockCookies.Object);
_mockHttpContext.Setup(c => c.Response).Returns(_mockResponse.Object);
_mockHttpContext.Setup(c => c.Request).Returns(_mockRequest.Object);
_model.PageContext.HttpContext = _mockHttpContext.Object;
_model.Url = _mockUrlHelper.Object;
}

[Fact]
public void OnGet_ClearsFormSectionTempData()
{
_mockTempDataService.Setup(c => c.Keys).Returns(["Form_Whatever_Questions"]);
_model.OnGet("en", "/foo");

_mockTempDataService.Verify(c => c.Remove("Form_Whatever_Questions"), Times.Once);
}

[Fact]
public void OnGet_SetsCookie_WhenLanguageIsEnglish()
{
var cookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture("en"));

_model.OnGet("en", "/foo");

_mockCookies.Verify(c => c.Append(It.IsAny<string>(), cookieValue, It.IsAny<CookieOptions>()), Times.Once);
}

[Fact]
public void OnGet_SetsCookie_WhenLanguageIsWelsh()
{
var cookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture("cy"));

_model.OnGet("cy", "/foo");

_mockCookies.Verify(c => c.Append(It.IsAny<string>(), cookieValue, It.IsAny<CookieOptions>()), Times.Once);
}

[Fact]
public void OnGet_Redirects_WhenRedirectUrlIsLocal()
{
var cookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture("cy"));

_mockUrlHelper.Setup(u => u.IsLocalUrl(It.IsAny<string>())).Returns(true);

var response = _model.OnGet("cy", "/foo");

response.Should().BeOfType<LocalRedirectResult>();

var localRedirectResult = response as LocalRedirectResult;
localRedirectResult!.Url.Should().Be("/foo");
}

[Fact]
public void OnGet_Redirects_WhenRedirectUrlIsRemote()
{
var cookieValue = CookieRequestCultureProvider.MakeCookieValue(new RequestCulture("cy"));

var response = _model.OnGet("cy", "http://whatever.com");

response.Should().BeOfType<RedirectResult>();

var redirectResult = response as RedirectResult;
redirectResult!.Url.Should().Be("/");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public async Task OnPost_WhenModelStateIsValid_And_CompaniesNumber_Provided_Shou

organisationClientMock.Setup(o => o.LookupOrganisationAsync(string.Empty, It.IsAny<string>()))
.Throws(new ApiException(string.Empty, 404, string.Empty, null, null));

var profile = GivenProfileOnCompaniesHouse(organisationName: "Acme Ltd");
companiesHouseApiMock.Setup(ch => ch.GetProfile(model.CompaniesHouseNumber))
.ReturnsAsync(profile);
Expand All @@ -88,7 +88,7 @@ public async Task OnPost_WhenModelStateIsValidAndRedirectToSummary_ShouldRedirec
model.HasCompaniesHouseNumber = true;
model.RedirectToSummary = true;
model.CompaniesHouseNumber = "123456";

GivenRegistrationIsInProgress(model.HasCompaniesHouseNumber, model.CompaniesHouseNumber);

organisationClientMock.Setup(o => o.LookupOrganisationAsync(string.Empty, It.IsAny<string>()))
Expand All @@ -111,14 +111,16 @@ public async Task OnPost_WhenModelStateIsValidAndOrganisationAlreadyExists_Shoul
model.HasCompaniesHouseNumber = true;
model.RedirectToSummary = true;
model.CompaniesHouseNumber = "123456";
model.OrganisationId = new Guid();
model.OrganisationName = "Test company";

GivenRegistrationIsInProgress(model.HasCompaniesHouseNumber, model.CompaniesHouseNumber);

var result = await model.OnPost();

tempDataServiceMock.Verify(api => api.Put(
FlashMessageTypes.Important,
CompanyHouseNumberQuestionModel.NotificationBannerCompanyAlreadyRegistered), Times.Once);
model.NotificationBannerCompanyAlreadyRegistered), Times.Once);
result.Should().BeOfType<PageResult>();
}

Expand All @@ -140,7 +142,7 @@ public async Task OnPost_WhenModelStateIsValidAndCompanyNotFoundAtComapniesHouse

tempDataServiceMock.Verify(api => api.Put(
FlashMessageTypes.Important,
CompanyHouseNumberQuestionModel.NotificationBannerCompanyNotFound), Times.Once);
model.NotificationBannerCompanyNotFound), Times.Once);
result.Should().BeOfType<PageResult>();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using CO.CDP.Organisation.WebApiClient;
using CO.CDP.OrganisationApp.Pages.Registration;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Moq;

namespace CO.CDP.OrganisationApp.Tests.Pages.Registration;

public class JoinOrganisationSuccessModelTests
{
private readonly Mock<IOrganisationClient> _organisationClientMock;
private readonly JoinOrganisationSuccessModel _joinOrganisationSuccessModel;
private readonly Guid _organisationId = Guid.NewGuid();
private readonly Guid _personId = Guid.NewGuid();
private readonly CO.CDP.Organisation.WebApiClient.Organisation _organisation;

public JoinOrganisationSuccessModelTests()
{
_organisationClientMock = new Mock<IOrganisationClient>();
_joinOrganisationSuccessModel = new JoinOrganisationSuccessModel(_organisationClientMock.Object);
_organisation = new CO.CDP.Organisation.WebApiClient.Organisation(null, null, null, null, _organisationId, null, "Test Org", []);
}

[Fact]
public async Task OnGet_ValidOrganisationId_ReturnsPageResult()
{
var organisationId = Guid.NewGuid();

_organisationClientMock.Setup(client => client.GetOrganisationAsync(organisationId))
.ReturnsAsync(_organisation);

var result = await _joinOrganisationSuccessModel.OnGet(organisationId);

result.Should().BeOfType<PageResult>();
_joinOrganisationSuccessModel.OrganisationDetails.Should().Be(_organisation);
_organisationClientMock.Verify(client => client.GetOrganisationAsync(organisationId), Times.Once);
}

[Fact]
public async Task OnGet_OrganisationNotFound_ReturnsRedirectToPageNotFound()
{
_organisationClientMock.Setup(client => client.GetOrganisationAsync(_organisationId))
.ThrowsAsync(new ApiException("Not Found", 404, "Not Found", null, null));

var result = await _joinOrganisationSuccessModel.OnGet(_organisationId);

result.Should().BeOfType<RedirectResult>()
.Which.Url.Should().Be("/page-not-found");

_organisationClientMock.Verify(client => client.GetOrganisationAsync(_organisationId), Times.Once);
}
}
Loading

0 comments on commit 438ef18

Please sign in to comment.