Skip to content

Commit

Permalink
Chore/382 consistent timezone (#389)
Browse files Browse the repository at this point in the history
* Remove usage of DateTime.Now in favor of DateTime.UtcNow

Use DateTime.UtcNow
Added some tests
Remove Console.WriteLines

* Add some simple tests for DefaultEFormidlingService

* Fix code smells

* Implement suggestions from review
  • Loading branch information
tjololo authored Jan 9, 2024
1 parent 97da907 commit 45cfc6d
Show file tree
Hide file tree
Showing 8 changed files with 340 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,7 @@ public RequestPartValidator(Application appInfo)
}
else
{
Console.WriteLine($"// {DateTime.Now} // Debug // Part : {part}");
Console.WriteLine($"// {DateTime.Now} // Debug // Part name: {part.Name}");
Console.WriteLine($"// {DateTime.Now} // Debug // appinfo : {appInfo}");
Console.WriteLine($"// {DateTime.Now} // Debug // appinfo.Id : {appInfo.Id}");

DataType? dataType = appInfo.DataTypes.Find(e => e.Id == part.Name);

Console.WriteLine($"// {DateTime.Now} // Debug // elementType : {dataType}");

if (dataType == null)
{
return $"Multipart section named, '{part.Name}' does not correspond to an element type in application metadata";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
using Altinn.App.Core.Constants;
using Altinn.App.Core.EFormidling.Interface;
using Altinn.App.Core.Internal.App;
using Altinn.App.Core.Internal.Auth;
using Altinn.App.Core.Internal.Data;
using Altinn.App.Core.Internal.Events;
using Altinn.App.Core.Models;
using Altinn.Common.AccessTokenClient.Services;
using Altinn.Common.EFormidlingClient;
using Altinn.Common.EFormidlingClient.Models.SBD;
using Altinn.Platform.Storage.Interface.Models;
using AltinnCore.Authentication.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

Expand All @@ -23,7 +22,7 @@ public class DefaultEFormidlingService : IEFormidlingService
{
private readonly ILogger<DefaultEFormidlingService> _logger;
private readonly IAccessTokenGenerator? _tokenGenerator;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IUserTokenProvider _userTokenProvider;
private readonly AppSettings? _appSettings;
private readonly PlatformSettings? _platformSettings;
private readonly IEFormidlingClient? _eFormidlingClient;
Expand All @@ -38,7 +37,7 @@ public class DefaultEFormidlingService : IEFormidlingService
/// </summary>
public DefaultEFormidlingService(
ILogger<DefaultEFormidlingService> logger,
IHttpContextAccessor httpContextAccessor,
IUserTokenProvider userTokenProvider,
IAppMetadata appMetadata,
IDataClient dataClient,
IEFormidlingReceivers eFormidlingReceivers,
Expand All @@ -51,9 +50,9 @@ public DefaultEFormidlingService(
{
_logger = logger;
_tokenGenerator = tokenGenerator;
_httpContextAccessor = httpContextAccessor;
_appSettings = appSettings?.Value;
_platformSettings = platformSettings?.Value;
_userTokenProvider = userTokenProvider;
_eFormidlingClient = eFormidlingClient;
_eFormidlingMetadata = eFormidlingMetadata;
_appMetadata = appMetadata;
Expand All @@ -76,7 +75,7 @@ public async Task SendEFormidlingShipment(Instance instance)
ApplicationMetadata applicationMetadata = await _appMetadata.GetApplicationMetadata();

string accessToken = _tokenGenerator.GenerateAccessToken(applicationMetadata.Org, applicationMetadata.AppIdentifier.App);
string authzToken = JwtTokenUtil.GetTokenFromContext(_httpContextAccessor.HttpContext, _appSettings.RuntimeCookieName);
string authzToken = _userTokenProvider.GetUserToken();

var requestHeaders = new Dictionary<string, string>
{
Expand Down Expand Up @@ -114,7 +113,7 @@ public async Task SendEFormidlingShipment(Instance instance)
private async Task<StandardBusinessDocument> ConstructStandardBusinessDocument(string instanceGuid,
Instance instance)
{
DateTime completedTime = DateTime.Now;
DateTime completedTime = DateTime.UtcNow;

Sender digdirSender = new Sender
{
Expand Down
2 changes: 1 addition & 1 deletion src/Altinn.App.Core/Features/Validation/ValidationAppSI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public async Task<List<ValidationIssue>> ValidateAndUpdateProcess(Instance insta
// The condition for completion is met if there are no errors (or other weirdnesses).
CanCompleteTask = messages.Count == 0 ||
messages.All(m => m.Severity != ValidationIssueSeverity.Error && m.Severity != ValidationIssueSeverity.Unspecified),
Timestamp = DateTime.Now
Timestamp = DateTime.UtcNow
};

await _instanceClient.UpdateProcess(instance);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public async Task Get_ShouldReturnProcessTasks()
"altinnTaskType": "data",
"ended": null,
"validated": {
"timestamp": "2020-02-07T10:46:36.985894+01:00",
"timestamp": "2020-02-07T10:46:36.985894Z",
"canCompleteTask": false
},
"flowType": null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"name": "Utfylling",
"altinnTaskType": "data",
"validated": {
"timestamp": "2020-02-07T10:46:36.985894+01:00",
"timestamp": "2020-02-07T10:46:36.985894Z",
"canCompleteTask": false
}
}
Expand Down
2 changes: 1 addition & 1 deletion test/Altinn.App.Api.Tests/Mocks/DataClientMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ public Task<DataElement> UpdateData<T>(T dataToSerialize, Guid instanceGuid, Typ
serializer.Serialize(stream, dataToSerialize);
}

dataElement.LastChanged = DateTime.Now;
dataElement.LastChanged = DateTime.UtcNow;
WriteDataElementToFile(dataElement, org, app, instanceOwnerPartyId);

return Task.FromResult(dataElement);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
using Altinn.App.Core.Configuration;
using Altinn.App.Core.Constants;
using Altinn.App.Core.EFormidling;
using Altinn.App.Core.EFormidling.Implementation;
using Altinn.App.Core.EFormidling.Interface;
using Altinn.App.Core.Internal.App;
using Altinn.App.Core.Internal.Auth;
using Altinn.App.Core.Internal.Data;
using Altinn.App.Core.Internal.Events;
using Altinn.App.Core.Models;
using Altinn.Common.AccessTokenClient.Services;
using Altinn.Common.EFormidlingClient;
using Altinn.Common.EFormidlingClient.Models.SBD;
using Altinn.Platform.Storage.Interface.Models;
using FluentAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using Xunit;

namespace Altinn.App.Core.Tests.Eformidling.Implementation;

public class DefaultEFormidlingServiceTests
{
[Fact]
public void SendEFormidlingShipment()
{
// Arrange
var logger = new NullLogger<DefaultEFormidlingService>();
var userTokenProvider = new Mock<IUserTokenProvider>();
var appMetadata = new Mock<IAppMetadata>();
var dataClient = new Mock<IDataClient>();
var eFormidlingReceivers = new Mock<IEFormidlingReceivers>();
var eventClient = new Mock<IEventsClient>();
var appSettings = Options.Create(new AppSettings
{
RuntimeCookieName = "AltinnStudioRuntime",
EFormidlingSender = "980123456",
});
var platformSettings = Options.Create(new PlatformSettings
{
SubscriptionKey = "subscription-key"
});
var eFormidlingClient = new Mock<IEFormidlingClient>();
var tokenGenerator = new Mock<IAccessTokenGenerator>();
var eFormidlingMetadata = new Mock<IEFormidlingMetadata>();
var instance = new Instance
{
Id = "1337/41C1099C-7EDD-47F5-AD1F-6267B497796F",
InstanceOwner = new InstanceOwner
{
PartyId = "1337",
},
Data = new List<DataElement>()
};

appMetadata.Setup(a => a.GetApplicationMetadata()).ReturnsAsync(new ApplicationMetadata("ttd/test-app")
{
Org = "ttd",
EFormidling = new EFormidlingContract
{
Process = "urn:no:difi:profile:arkivmelding:plan:3.0",
Standard = "urn:no:difi:arkivmelding:xsd::arkivmelding",
TypeVersion = "v8",
Type = "arkivmelding",
SecurityLevel = 3,
DataTypes = new List<string>()
}
});
tokenGenerator.Setup(t => t.GenerateAccessToken("ttd", "test-app")).Returns("access-token");
userTokenProvider.Setup(u => u.GetUserToken()).Returns("authz-token");
eFormidlingReceivers.Setup(er => er.GetEFormidlingReceivers(instance)).ReturnsAsync(new List<Receiver>());
eFormidlingMetadata.Setup(em => em.GenerateEFormidlingMetadata(instance)).ReturnsAsync(() =>
{
return ("fakefilename.txt", Stream.Null);
});

var defaultEformidlingService = new DefaultEFormidlingService(
logger,
userTokenProvider.Object,
appMetadata.Object,
dataClient.Object,
eFormidlingReceivers.Object,
eventClient.Object,
appSettings,
platformSettings,
eFormidlingClient.Object,
tokenGenerator.Object,
eFormidlingMetadata.Object);

// Act
var result = defaultEformidlingService.SendEFormidlingShipment(instance);

// Assert
var expectedReqHeaders = new Dictionary<string, string>
{
{ "Authorization", $"Bearer authz-token" },
{ General.EFormidlingAccessTokenHeaderName, "access-token" },
{ General.SubscriptionKeyHeaderName, "subscription-key" }
};

appMetadata.Verify(a => a.GetApplicationMetadata());
tokenGenerator.Verify(t => t.GenerateAccessToken("ttd", "test-app"));
userTokenProvider.Verify(u => u.GetUserToken());
eFormidlingReceivers.Verify(er => er.GetEFormidlingReceivers(instance));
eFormidlingMetadata.Verify(em => em.GenerateEFormidlingMetadata(instance));
eFormidlingClient.Verify(ec => ec.CreateMessage(It.IsAny<StandardBusinessDocument>(), expectedReqHeaders));
eFormidlingClient.Verify(ec => ec.UploadAttachment(Stream.Null, "41C1099C-7EDD-47F5-AD1F-6267B497796F", "fakefilename.txt", expectedReqHeaders));
eFormidlingClient.Verify(ec => ec.SendMessage("41C1099C-7EDD-47F5-AD1F-6267B497796F", expectedReqHeaders));
eventClient.Verify(e => e.AddEvent(EformidlingConstants.CheckInstanceStatusEventType, instance));

eFormidlingClient.VerifyNoOtherCalls();
eventClient.VerifyNoOtherCalls();
tokenGenerator.VerifyNoOtherCalls();
userTokenProvider.VerifyNoOtherCalls();
eFormidlingReceivers.VerifyNoOtherCalls();
appMetadata.VerifyNoOtherCalls();

result.IsCompletedSuccessfully.Should().BeTrue();
}

[Fact]
public void SendEFormidlingShipment_throws_exception_if_send_fails()
{
// Arrange
var logger = new NullLogger<DefaultEFormidlingService>();
var userTokenProvider = new Mock<IUserTokenProvider>();
var appMetadata = new Mock<IAppMetadata>();
var dataClient = new Mock<IDataClient>();
var eFormidlingReceivers = new Mock<IEFormidlingReceivers>();
var eventClient = new Mock<IEventsClient>();
var appSettings = Options.Create(new AppSettings
{
RuntimeCookieName = "AltinnStudioRuntime",
EFormidlingSender = "980123456",
});
var platformSettings = Options.Create(new PlatformSettings
{
SubscriptionKey = "subscription-key",
});
var eFormidlingClient = new Mock<IEFormidlingClient>();
var tokenGenerator = new Mock<IAccessTokenGenerator>();
var eFormidlingMetadata = new Mock<IEFormidlingMetadata>();
var instance = new Instance
{
Id = "1337/41C1099C-7EDD-47F5-AD1F-6267B497796F",
InstanceOwner = new InstanceOwner
{
PartyId = "1337",
},
Data = new List<DataElement>()
};

appMetadata.Setup(a => a.GetApplicationMetadata()).ReturnsAsync(new ApplicationMetadata("ttd/test-app")
{
Org = "ttd",
EFormidling = new EFormidlingContract
{
Process = "urn:no:difi:profile:arkivmelding:plan:3.0",
Standard = "urn:no:difi:arkivmelding:xsd::arkivmelding",
TypeVersion = "v8",
Type = "arkivmelding",
SecurityLevel = 3,
DataTypes = new List<string>()
}
});
tokenGenerator.Setup(t => t.GenerateAccessToken("ttd", "test-app")).Returns("access-token");
userTokenProvider.Setup(u => u.GetUserToken()).Returns("authz-token");
eFormidlingReceivers.Setup(er => er.GetEFormidlingReceivers(instance)).ReturnsAsync(new List<Receiver>());
eFormidlingMetadata.Setup(em => em.GenerateEFormidlingMetadata(instance)).ReturnsAsync(() =>
{
return ("fakefilename.txt", Stream.Null);
});
eFormidlingClient.Setup(ec => ec.SendMessage(It.IsAny<string>(), It.IsAny<Dictionary<string, string>>()))
.ThrowsAsync(new Exception("XUnit expected exception"));

var defaultEformidlingService = new DefaultEFormidlingService(
logger,
userTokenProvider.Object,
appMetadata.Object,
dataClient.Object,
eFormidlingReceivers.Object,
eventClient.Object,
appSettings,
platformSettings,
eFormidlingClient.Object,
tokenGenerator.Object,
eFormidlingMetadata.Object);

// Act
var result = defaultEformidlingService.SendEFormidlingShipment(instance);

// Assert
// Assert
var expectedReqHeaders = new Dictionary<string, string>
{
{ "Authorization", $"Bearer authz-token" },
{ General.EFormidlingAccessTokenHeaderName, "access-token" },
{ General.SubscriptionKeyHeaderName, "subscription-key" }
};

appMetadata.Verify(a => a.GetApplicationMetadata());
tokenGenerator.Verify(t => t.GenerateAccessToken("ttd", "test-app"));
userTokenProvider.Verify(u => u.GetUserToken());
eFormidlingReceivers.Verify(er => er.GetEFormidlingReceivers(instance));
eFormidlingMetadata.Verify(em => em.GenerateEFormidlingMetadata(instance));
eFormidlingClient.Verify(ec => ec.CreateMessage(It.IsAny<StandardBusinessDocument>(), expectedReqHeaders));
eFormidlingClient.Verify(ec => ec.UploadAttachment(Stream.Null, "41C1099C-7EDD-47F5-AD1F-6267B497796F", "fakefilename.txt", expectedReqHeaders));
eFormidlingClient.Verify(ec => ec.SendMessage("41C1099C-7EDD-47F5-AD1F-6267B497796F", expectedReqHeaders));

eFormidlingClient.VerifyNoOtherCalls();
eventClient.VerifyNoOtherCalls();
tokenGenerator.VerifyNoOtherCalls();
userTokenProvider.VerifyNoOtherCalls();
eFormidlingReceivers.VerifyNoOtherCalls();
appMetadata.VerifyNoOtherCalls();

result.IsCompletedSuccessfully.Should().BeFalse();
}
}
Loading

0 comments on commit 45cfc6d

Please sign in to comment.