From 7f562dd57fe7c0299d29f2312b7a84ef170fca78 Mon Sep 17 00:00:00 2001 From: Ivar Nesje Date: Fri, 1 Mar 2024 09:23:03 +0100 Subject: [PATCH] Add pipeline job to verify clean dotnet format (#455) * Try to make git checkout cs files with crlf endings * Fix non async .Result in tests * Add pipeline job for dotnet-format * Actually run dotnet format --- .gitattributes | 2 + .github/workflows/dotnet-format.yml | 19 +++ .../Controllers/AccountController.cs | 2 +- .../Controllers/DataController.cs | 2 +- .../Controllers/DataListsController.cs | 2 +- .../Controllers/DataTagsController.cs | 2 +- .../Controllers/EventsReceiverController.cs | 4 +- .../Controllers/InstancesController.cs | 12 +- .../Controllers/PdfController.cs | 4 +- .../Controllers/ProcessController.cs | 20 +-- .../Controllers/ProfileController.cs | 2 +- .../Controllers/StatelessDataController.cs | 2 +- .../Controllers/StatelessPagesController.cs | 4 +- .../Controllers/ValidateController.cs | 8 +- .../WebApplicationBuilderExtensions.cs | 2 +- .../DataRestrictionValidation.cs | 4 +- src/Altinn.App.Api/Helpers/StartupHelper.cs | 2 +- .../Middleware/SecurityHeadersMiddleware.cs | 8 +- src/Altinn.App.Api/Models/AppProcessState.cs | 2 +- src/Altinn.App.Api/Models/DataPatchRequest.cs | 2 +- .../Models/InstanceFileScanResult.cs | 2 +- .../Models/UserActionRequest.cs | 4 +- .../Models/UserActionResponse.cs | 4 +- .../Extensions/ServiceCollectionExtensions.cs | 6 +- .../DefaultEFormidlingReceivers.cs | 2 +- .../DefaultEFormidlingService.cs | 2 +- .../EformidlingStatusCheckEventHandler.cs | 2 +- .../Extensions/HttpClientExtension.cs | 2 +- .../Extensions/ProcessStateExtensions.cs | 2 +- .../Features/Action/SigningUserAction.cs | 4 +- .../Action/UniqueSignatureAuthorizer.cs | 2 +- .../Action/UserActionAuthorizerContext.cs | 2 +- .../DataLists/NullInstanceDataListProvider.cs | 2 +- .../NullInstantiationProcessor.cs | 2 +- .../FileAnalyzis/FileAnalysisResult.cs | 4 +- .../Features/IInstanceValidator.cs | 2 +- .../Features/IProcessTaskEnd.cs | 2 +- .../Features/IProcessTaskStart.cs | 2 +- src/Altinn.App.Core/Features/IUserAction.cs | 2 +- .../Altinn2CodeListProvider.cs | 2 +- .../Altinn2MetadataApiClient.cs | 2 +- .../Options/DefaultAppOptionsProvider.cs | 2 +- .../Default/DefaultDataElementValidator.cs | 10 +- .../Validation/Default/RequiredValidator.cs | 2 +- .../Validation/GenericFormDataValidator.cs | 2 +- .../Validation/Helpers/ModelStateHelpers.cs | 2 +- .../Validation/NullInstantiationValidator.cs | 2 +- .../Helpers/DataModel/DataModelException.cs | 2 +- .../Helpers/MultiDecisionHelper.cs | 4 +- .../Helpers/RemoveBomExtentions.cs | 2 +- .../Helpers/ServiceException.cs | 2 +- .../Implementation/DefaultAppEvents.cs | 12 +- .../Authorization/AuthorizationClient.cs | 2 +- .../Events/EventsSubscriptionClient.cs | 8 +- .../Clients/KeyVault/SecretsLocalClient.cs | 2 +- .../Clients/Register/RegisterERClient.cs | 2 +- .../Clients/Storage/DataClient.cs | 10 +- .../Storage/InstanceClientMetricsDecorator.cs | 2 +- .../Clients/Storage/ProcessClient.cs | 2 +- .../Clients/Storage/SignClient.cs | 10 +- src/Altinn.App.Core/Interface/IAppEvents.cs | 2 +- src/Altinn.App.Core/Interface/IData.cs | 2 +- src/Altinn.App.Core/Interface/IInstance.cs | 4 +- src/Altinn.App.Core/Interface/ITaskEvents.cs | 6 +- .../Internal/App/AppMetadata.cs | 2 +- .../App/ApplicationConfigException.cs | 2 +- .../Internal/App/IAppEvents.cs | 2 +- .../Internal/App/IAppMetadata.cs | 4 +- .../Internal/AppModel/DefaultAppModel.cs | 6 +- .../Internal/Auth/AuthorizationService.cs | 8 +- .../Internal/Auth/IAuthorizationClient.cs | 2 +- .../Internal/Auth/IAuthorizationService.cs | 2 +- .../Internal/Data/IDataClient.cs | 6 +- .../Events/SubscriptionValidationHandler.cs | 2 +- .../ExpressionEvaluatorTypeErrorException.cs | 4 +- .../Internal/Instances/IInstanceClient.cs | 4 +- .../Internal/Patch/DataPatchError.cs | 2 +- .../Internal/Pdf/PdfService.cs | 8 +- .../Action/IUserActionAuthorizerProvider.cs | 4 +- .../Action/UserActionAuthorizerProvider.cs | 10 +- ...ionAuthorizerServiceCollectionExtension.cs | 8 +- .../AltinnExtensionProperties/AltinnAction.cs | 4 +- .../AltinnSignatureConfiguration.cs | 4 +- .../AltinnTaskExtension.cs | 4 +- .../Process/Elements/AppProcessElementInfo.cs | 18 +-- .../Process/Elements/AppProcessState.cs | 6 +- .../Internal/Process/Elements/EndEvent.cs | 2 +- .../Process/Elements/ExclusiveGateway.cs | 4 +- .../Process/Elements/ExtensionElements.cs | 2 +- .../Internal/Process/Elements/NullTask.cs | 2 +- .../Internal/Process/Elements/ProcessTask.cs | 2 +- .../Internal/Process/Elements/SequenceFlow.cs | 2 +- .../Internal/Process/Elements/StartEvent.cs | 2 +- .../Internal/Process/Elements/TaskBase.cs | 2 +- .../Internal/Process/Elements/UserAction.cs | 4 +- .../Internal/Process/IProcessReader.cs | 20 +-- .../Internal/Process/ITaskEvents.cs | 6 +- .../Internal/Process/ProcessEngine.cs | 2 +- .../Process/ProcessEngineMetricsDecorator.cs | 6 +- .../Process/ProcessEventDispatcher.cs | 12 +- .../Internal/Process/ProcessNavigator.cs | 7 +- .../Internal/Process/ProcessReader.cs | 4 +- .../Internal/Sign/SignatureContext.cs | 18 +-- .../Validation/FileValidationService.cs | 2 +- src/Altinn.App.Core/Models/AppIdentifier.cs | 4 +- src/Altinn.App.Core/Models/CloudEvent.cs | 2 +- src/Altinn.App.Core/Models/DataList.cs | 2 +- .../Models/InstanceIdentifier.cs | 4 +- src/Altinn.App.Core/Models/MimeType.cs | 2 +- src/Altinn.App.Core/Models/OnEntry.cs | 8 +- .../Models/Process/ProcessChangeResult.cs | 6 +- .../Models/Result/ServiceResult.cs | 4 +- .../Models/UserAction/ActionError.cs | 2 +- .../Models/UserAction/UserActionContext.cs | 6 +- .../Models/UserAction/UserActionResult.cs | 6 +- .../Controllers/DataControllerTests.cs | 7 +- .../Controllers/DataController_PutTests.cs | 12 +- .../EventsReceiverControllerTests.cs | 4 +- .../InstancesController_CopyInstanceTests.cs | 24 ++-- .../Controllers/PdfControllerTests.cs | 20 +-- .../StatelessDataControllerTests.cs | 38 +++--- .../StatelessPagesControllerTests.cs | 10 +- .../Controllers/TestResources/DummyModel.cs | 7 +- .../Controllers/TextsControllerTests.cs | 20 +-- ...alidateController_ValidateInstanceTests.cs | 8 +- test/Altinn.App.Api.Tests/Data/TestData.cs | 10 +- .../apps/tdd/eformidling-app/logic/App.cs | 2 +- .../DataRestrictionValidationTests.cs | 2 +- .../Helpers/StartupHelperTests.cs | 2 +- .../Mappers/SimpleInstanceMapperTests.cs | 10 +- .../Mocks/AppModelMock.cs | 2 +- .../Mocks/AuthorizationMock.cs | 4 +- .../Mocks/InstanceClientMockSi.cs | 20 +-- test/Altinn.App.Api.Tests/Program.cs | 2 +- .../SwaggerIncludeXmlCommentsTestDouble.cs | 2 +- .../Utils/PrincipalUtil.cs | 2 +- .../NullInstanceDataListProviderTest.cs | 5 +- .../DefaultEFormidlingServiceTests.cs | 22 ++-- .../Extensions/DictionaryExtensionsTests.cs | 2 +- .../Extensions/ProcessStateExtensionTests.cs | 2 +- .../Features/Action/SigningUserActionTests.cs | 8 +- .../Action/UniqueSignatureAuthorizerTests.cs | 18 +-- .../Features/Action/UserActionServiceTests.cs | 10 +- .../GenericDataProcessorTests.cs | 4 +- .../Default/ExpressionValidatorTests.cs | 2 +- .../Validators/ValidationServiceOldTests.cs | 8 +- .../Helpers/JsonDataModel.cs | 2 - .../Helpers/JsonHelperTests.cs | 2 +- .../Helpers/MimeTypeMapTests.cs | 2 +- .../Helpers/MultiDecisionHelperTests.cs | 22 ++-- .../Helpers/ProcessHelperTests.cs | 26 ++-- .../Helpers/RemoveBomExtentionsTests.cs | 2 +- .../Helpers/ShadowFieldsConverterTests.cs | 2 +- .../Implementation/AppResourcesSITests.cs | 2 +- .../Implementation/DefaultTaskEventsTests.cs | 20 +-- .../Implementation/NullPdfFormatterTests.cs | 6 +- .../AppDataModel/ModelWithShadowFields.cs | 116 +++++++++--------- .../Authorization/AuthorizationClientTests.cs | 14 +-- .../Clients/Storage/DataClientTests.cs | 4 +- .../Clients/Storage/SignClientTests.cs | 8 +- .../Clients/Storage/TestData/ExampleModel.cs | 2 +- .../Internal/App/AppMedataTest.cs | 2 +- .../Events/EventHandlerResolverTests.cs | 7 +- .../Internal/Patch/PatchServiceTests.cs | 8 +- .../Internal/Pdf/PdfServiceTests.cs | 2 +- .../TestData/UserActionAuthorizerStub.cs | 2 +- ...thorizerServiceCollectionExtensionTests.cs | 2 +- .../Process/Elements/AppProcessStateTests.cs | 4 +- .../ExpressionsExclusiveGatewayTests.cs | 4 +- .../ProcessEngineMetricsDecoratorTests.cs | 48 ++++---- .../Internal/Process/ProcessEngineTest.cs | 2 +- .../Internal/Process/ProcessNavigatorTests.cs | 98 +++++++-------- .../Process/TestUtils/ProcessTestUtils.cs | 4 +- .../CommonTests/ExpressionTestCaseRoot.cs | 2 +- .../TestBackendExclusiveFunctions.cs | 2 +- .../CommonTests/TestFunctions.cs | 16 +-- .../LayoutExpressions/TestDataModel.cs | 1 - .../Models/AppIdentifierTests.cs | 4 +- .../Models/ApplicationMetdataTests.cs | 4 +- .../Models/InstanceIdentifierTests.cs | 2 +- .../Models/MimeTypeTests.cs | 14 +-- .../Models/PageComponentConverterTests.cs | 1 - .../Models/Result/ServiceResultTests.cs | 4 +- .../Altinn2Provider/Altinn2OptionsTests.cs | 2 +- .../Options/AppOptionsFactoryTests.cs | 2 +- .../NullInstanceAppOptionsProviderTests.cs | 5 +- 186 files changed, 653 insertions(+), 618 deletions(-) create mode 100644 .github/workflows/dotnet-format.yml diff --git a/.gitattributes b/.gitattributes index 1ff0c4230..c61221a5b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,6 +3,8 @@ ############################################################################### * text=auto +*.cs text eol=crlf + ############################################################################### # Set default behavior for command prompt diff. # diff --git a/.github/workflows/dotnet-format.yml b/.github/workflows/dotnet-format.yml new file mode 100644 index 000000000..90168bc7a --- /dev/null +++ b/.github/workflows/dotnet-format.yml @@ -0,0 +1,19 @@ +name: Verify dotnet format + +on: + pull_request: + branches: [ "main", "v8" ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Setup .NET + uses: actions/setup-dotnet@v3 + with: + dotnet-version: 8.0.x + - name: Verify dotnet format + run: dotnet format --verify-no-changes diff --git a/src/Altinn.App.Api/Controllers/AccountController.cs b/src/Altinn.App.Api/Controllers/AccountController.cs index 7065de804..687a54c01 100644 --- a/src/Altinn.App.Api/Controllers/AccountController.cs +++ b/src/Altinn.App.Api/Controllers/AccountController.cs @@ -4,7 +4,7 @@ using Microsoft.Extensions.Options; namespace Altinn.App.Api.Controllers -{ +{ /// /// To handle authentication related operations /// diff --git a/src/Altinn.App.Api/Controllers/DataController.cs b/src/Altinn.App.Api/Controllers/DataController.cs index 3a4423c67..0fb96982f 100644 --- a/src/Altinn.App.Api/Controllers/DataController.cs +++ b/src/Altinn.App.Api/Controllers/DataController.cs @@ -422,7 +422,7 @@ public async Task> PatchFormData( { await UpdateDataValuesOnInstance(instance, dataType.Id, res.Ok.NewDataModel); await UpdatePresentationTextsOnInstance(instance, dataType.Id, res.Ok.NewDataModel); - + return Ok(new DataPatchResponse { NewDataModel = res.Ok.NewDataModel, diff --git a/src/Altinn.App.Api/Controllers/DataListsController.cs b/src/Altinn.App.Api/Controllers/DataListsController.cs index 7f6070f2a..c05a1b921 100644 --- a/src/Altinn.App.Api/Controllers/DataListsController.cs +++ b/src/Altinn.App.Api/Controllers/DataListsController.cs @@ -9,7 +9,7 @@ namespace Altinn.App.Api.Controllers /// Represents the DataLists API. /// [ApiController] - public class DataListsController: ControllerBase + public class DataListsController : ControllerBase { private readonly IDataListsService _dataListsService; diff --git a/src/Altinn.App.Api/Controllers/DataTagsController.cs b/src/Altinn.App.Api/Controllers/DataTagsController.cs index 7b6b9cd19..e29176b0e 100644 --- a/src/Altinn.App.Api/Controllers/DataTagsController.cs +++ b/src/Altinn.App.Api/Controllers/DataTagsController.cs @@ -113,7 +113,7 @@ public async Task> Add( } DataElement? dataElement = instance.Data.FirstOrDefault(m => m.Id.Equals(dataGuid.ToString())); - + if (dataElement == null) { return NotFound("Unable to find data element based on the given parameters."); diff --git a/src/Altinn.App.Api/Controllers/EventsReceiverController.cs b/src/Altinn.App.Api/Controllers/EventsReceiverController.cs index 891a83cf5..83b063765 100644 --- a/src/Altinn.App.Api/Controllers/EventsReceiverController.cs +++ b/src/Altinn.App.Api/Controllers/EventsReceiverController.cs @@ -26,8 +26,8 @@ public class EventsReceiverController : ControllerBase /// Initializes a new instance of the class. /// public EventsReceiverController( - IEventHandlerResolver eventHandlerResolver, - ILogger logger, + IEventHandlerResolver eventHandlerResolver, + ILogger logger, IOptions options, IEventSecretCodeProvider secretCodeProvider) { diff --git a/src/Altinn.App.Api/Controllers/InstancesController.cs b/src/Altinn.App.Api/Controllers/InstancesController.cs index a00b300dc..20e5ecdf9 100644 --- a/src/Altinn.App.Api/Controllers/InstancesController.cs +++ b/src/Altinn.App.Api/Controllers/InstancesController.cs @@ -84,8 +84,8 @@ public InstancesController( IEventsClient eventsClient, IOptions appSettings, IPrefill prefillService, - IProfileClient profileClient, - IProcessEngine processEngine, + IProfileClient profileClient, + IProcessEngine processEngine, IOrganizationClient orgClient) { _logger = logger; @@ -274,7 +274,7 @@ public async Task> Post( Instance instance; instanceTemplate.Process = null; ProcessStateChange? change = null; - + try { // start process and goto next task @@ -289,7 +289,7 @@ public async Task> Post( { return Conflict(result.ErrorMessage); } - + change = result.ProcessStateChange; // create the instance @@ -440,7 +440,7 @@ public async Task> PostSimplified( Dryrun = true, Prefill = instansiationInstance.Prefill }; - + processResult = await _processEngine.StartProcess(request); Instance? source = null; @@ -569,7 +569,7 @@ public async Task CopyInstance( { return StatusCode((int)HttpStatusCode.Forbidden, validationResult); } - + ProcessStartRequest processStartRequest = new() { Instance = targetInstance, diff --git a/src/Altinn.App.Api/Controllers/PdfController.cs b/src/Altinn.App.Api/Controllers/PdfController.cs index 0d1a991b7..eab927027 100644 --- a/src/Altinn.App.Api/Controllers/PdfController.cs +++ b/src/Altinn.App.Api/Controllers/PdfController.cs @@ -20,7 +20,7 @@ namespace Altinn.App.Api.Controllers public class PdfController : ControllerBase { private readonly IInstanceClient _instanceClient; - #pragma warning disable CS0618 // Type or member is obsolete +#pragma warning disable CS0618 // Type or member is obsolete private readonly IPdfFormatter _pdfFormatter; private readonly IAppResources _resources; private readonly IAppModel _appModel; @@ -40,7 +40,7 @@ public class PdfController : ControllerBase /// The PDF service public PdfController( IInstanceClient instanceClient, - #pragma warning disable CS0618 // Type or member is obsolete +#pragma warning disable CS0618 // Type or member is obsolete IPdfFormatter pdfFormatter, IAppResources resources, IAppModel appModel, diff --git a/src/Altinn.App.Api/Controllers/ProcessController.cs b/src/Altinn.App.Api/Controllers/ProcessController.cs index 6a5bfbd36..51b691a3f 100644 --- a/src/Altinn.App.Api/Controllers/ProcessController.cs +++ b/src/Altinn.App.Api/Controllers/ProcessController.cs @@ -133,7 +133,7 @@ public async Task> StartProcess( { return Conflict(result.ErrorMessage); } - + AppProcessState appProcessState = await ConvertAndAuthorizeActions(instance, result.ProcessStateChange?.NewProcessState); return Ok(appProcessState); } @@ -236,7 +236,7 @@ public async Task> NextElement( { processNext = await DeserializeFromStream(Request.Body); } - + Instance instance = await _instanceClient.GetInstance(app, org, instanceOwnerPartyId, instanceGuid); if (instance?.Process == null) @@ -264,7 +264,7 @@ public async Task> NextElement( { return Forbid(); } - + _logger.LogDebug("User is authorized to perform action {Action}", checkedAction); var request = new ProcessNextRequest() { @@ -439,7 +439,7 @@ public async Task GetProcessHistory( return ExceptionResponse(processException, $"Unable to find retrieve process history for instance {instanceOwnerPartyId}/{instanceGuid}. Exception: {processException}"); } } - + private async Task ConvertAndAuthorizeActions(Instance instance, ProcessState? processState) { AppProcessState appProcessState = new AppProcessState(processState); @@ -458,15 +458,15 @@ private async Task ConvertAndAuthorizeActions(Instance instance appProcessState.CurrentTask.UserActions = authDecisions; } } - + var processTasks = new List(); foreach (var processElement in _processReader.GetAllFlowElements().OfType()) { processTasks.Add(new AppProcessTaskTypeInfo - { - ElementId = processElement.Id, - AltinnTaskType = processElement.ExtensionElements?.TaskExtension?.TaskType - }); + { + ElementId = processElement.Id, + AltinnTaskType = processElement.ExtensionElements?.TaskExtension?.TaskType + }); } appProcessState.ProcessTasks = processTasks; @@ -534,7 +534,7 @@ private ActionResult HandlePlatformHttpException(PlatformHttpException e, string return ExceptionResponse(e, defaultMessage); } - + private static async Task DeserializeFromStream(Stream stream) { using StreamReader reader = new StreamReader(stream); diff --git a/src/Altinn.App.Api/Controllers/ProfileController.cs b/src/Altinn.App.Api/Controllers/ProfileController.cs index 6ff286f4a..7207b61be 100644 --- a/src/Altinn.App.Api/Controllers/ProfileController.cs +++ b/src/Altinn.App.Api/Controllers/ProfileController.cs @@ -52,7 +52,7 @@ public async Task GetUser() } catch (Exception e) { - return StatusCode(500, e.Message); + return StatusCode(500, e.Message); } } } diff --git a/src/Altinn.App.Api/Controllers/StatelessDataController.cs b/src/Altinn.App.Api/Controllers/StatelessDataController.cs index e47813d8f..6c896a4a5 100644 --- a/src/Altinn.App.Api/Controllers/StatelessDataController.cs +++ b/src/Altinn.App.Api/Controllers/StatelessDataController.cs @@ -127,7 +127,7 @@ private async Task ProcessAllDataRead(Instance virtualInstance, object appModel, foreach (var dataProcessor in _dataProcessors) { _logger.LogInformation( - "ProcessDataRead for {modelType} using {dataProcesor}", + "ProcessDataRead for {modelType} using {dataProcesor}", appModel.GetType().Name, dataProcessor.GetType().Name); await dataProcessor.ProcessDataRead(virtualInstance, null, appModel, language); diff --git a/src/Altinn.App.Api/Controllers/StatelessPagesController.cs b/src/Altinn.App.Api/Controllers/StatelessPagesController.cs index d59fa3c0f..302c07afa 100644 --- a/src/Altinn.App.Api/Controllers/StatelessPagesController.cs +++ b/src/Altinn.App.Api/Controllers/StatelessPagesController.cs @@ -30,8 +30,8 @@ public class StatelessPagesController : ControllerBase /// The app resource service /// The page order service public StatelessPagesController( - IAppModel appModel, - IAppResources resources, + IAppModel appModel, + IAppResources resources, IPageOrder pageOrder) { _appModel = appModel; diff --git a/src/Altinn.App.Api/Controllers/ValidateController.cs b/src/Altinn.App.Api/Controllers/ValidateController.cs index 22b83eb2f..18f038d85 100644 --- a/src/Altinn.App.Api/Controllers/ValidateController.cs +++ b/src/Altinn.App.Api/Controllers/ValidateController.cs @@ -63,14 +63,14 @@ public async Task ValidateInstance( throw new ValidationException("Unable to validate instance without a started process."); } - try + try { List messages = await _validationService.ValidateInstanceAtTask(instance, taskId, language); return Ok(messages); - } - catch (PlatformHttpException exception) + } + catch (PlatformHttpException exception) { - if (exception.Response.StatusCode == System.Net.HttpStatusCode.Forbidden) + if (exception.Response.StatusCode == System.Net.HttpStatusCode.Forbidden) { return StatusCode(403); } diff --git a/src/Altinn.App.Api/Extensions/WebApplicationBuilderExtensions.cs b/src/Altinn.App.Api/Extensions/WebApplicationBuilderExtensions.cs index 79093b836..1a4b21a5e 100644 --- a/src/Altinn.App.Api/Extensions/WebApplicationBuilderExtensions.cs +++ b/src/Altinn.App.Api/Extensions/WebApplicationBuilderExtensions.cs @@ -23,7 +23,7 @@ public static IApplicationBuilder UseAltinnAppCommonConfiguration(this IApplicat app.UseDeveloperExceptionPage(); webApp.UseAltinnPrometheus(appId); } - + app.UseHttpMetrics(); app.UseMetricServer(); app.UseDefaultSecurityHeaders(); diff --git a/src/Altinn.App.Api/Helpers/RequestHandling/DataRestrictionValidation.cs b/src/Altinn.App.Api/Helpers/RequestHandling/DataRestrictionValidation.cs index 8d4dff27a..5550e0b13 100644 --- a/src/Altinn.App.Api/Helpers/RequestHandling/DataRestrictionValidation.cs +++ b/src/Altinn.App.Api/Helpers/RequestHandling/DataRestrictionValidation.cs @@ -30,7 +30,7 @@ public static (bool Success, List Errors) CompliesWithDataRestr Severity = ValidationIssueSeverity.Error, Description = $"{errorBaseMessage} The request must include a Content-Disposition header" }); - + return (false, errors); } @@ -131,7 +131,7 @@ public static (bool Success, List Errors) CompliesWithDataRestr { ContentDispositionHeaderValue contentDisposition = ContentDispositionHeaderValue.Parse(headerValues); string? filename = contentDisposition.FileNameStar ?? contentDisposition.FileName; - + // We actively remove quotes because we don't want them replaced with '_'. // Quotes around filename in Content-Disposition is valid, but not as part of the filename. filename = filename?.Trim('\"').AsFileName(false); diff --git a/src/Altinn.App.Api/Helpers/StartupHelper.cs b/src/Altinn.App.Api/Helpers/StartupHelper.cs index 08bae042d..c645b85df 100644 --- a/src/Altinn.App.Api/Helpers/StartupHelper.cs +++ b/src/Altinn.App.Api/Helpers/StartupHelper.cs @@ -13,7 +13,7 @@ public static class StartupHelper /// Delegate for swagger funciton /// public delegate void SwaggerIncludeXmlComments(string filepath, bool a); - + /// /// Includes comments in swagger based on XML comment files /// diff --git a/src/Altinn.App.Api/Infrastructure/Middleware/SecurityHeadersMiddleware.cs b/src/Altinn.App.Api/Infrastructure/Middleware/SecurityHeadersMiddleware.cs index a78576762..ad2d2f6c1 100644 --- a/src/Altinn.App.Api/Infrastructure/Middleware/SecurityHeadersMiddleware.cs +++ b/src/Altinn.App.Api/Infrastructure/Middleware/SecurityHeadersMiddleware.cs @@ -31,10 +31,10 @@ public SecurityHeadersMiddleware(RequestDelegate next) /// public Task Invoke(HttpContext context) { - context.Response.Headers.Add("X-Frame-Options", "deny"); - context.Response.Headers.Add("X-Content-Type-Options", "nosniff"); - context.Response.Headers.Add("X-XSS-Protection", "0"); - context.Response.Headers.Add("Referer-Policy", "no-referer"); + context.Response.Headers.Append("X-Frame-Options", "deny"); + context.Response.Headers.Append("X-Content-Type-Options", "nosniff"); + context.Response.Headers.Append("X-XSS-Protection", "0"); + context.Response.Headers.Append("Referer-Policy", "no-referer"); return _next(context); } diff --git a/src/Altinn.App.Api/Models/AppProcessState.cs b/src/Altinn.App.Api/Models/AppProcessState.cs index 71f533877..13e5cf2cb 100644 --- a/src/Altinn.App.Api/Models/AppProcessState.cs +++ b/src/Altinn.App.Api/Models/AppProcessState.cs @@ -6,7 +6,7 @@ namespace Altinn.App.Api.Models; /// Extended representation of a status object that holds the process state of an application instance. /// The process is defined by the application's process specification BPMN file. /// -public class AppProcessState: ProcessState +public class AppProcessState : ProcessState { /// /// Actions that can be performed and if the user is allowed to perform them. diff --git a/src/Altinn.App.Api/Models/DataPatchRequest.cs b/src/Altinn.App.Api/Models/DataPatchRequest.cs index 69a602485..8ee4012c3 100644 --- a/src/Altinn.App.Api/Models/DataPatchRequest.cs +++ b/src/Altinn.App.Api/Models/DataPatchRequest.cs @@ -14,7 +14,7 @@ public class DataPatchRequest /// [JsonPropertyName("patch")] public required JsonPatch Patch { get; init; } - + /// /// List of validators to ignore during the patch operation. /// Issues from these validators will not be run during the save operation, but the validator will run on process/next diff --git a/src/Altinn.App.Api/Models/InstanceFileScanResult.cs b/src/Altinn.App.Api/Models/InstanceFileScanResult.cs index c2af6b0d2..9a8520c77 100644 --- a/src/Altinn.App.Api/Models/InstanceFileScanResult.cs +++ b/src/Altinn.App.Api/Models/InstanceFileScanResult.cs @@ -57,7 +57,7 @@ public void AddFileScanResult(DataElementFileScanResult dataElementFileScanResul _dataElements.Add(dataElementFileScanResult); RecalculateAggregatedStatus(); - } + } } private void RecalculateAggregatedStatus() diff --git a/src/Altinn.App.Api/Models/UserActionRequest.cs b/src/Altinn.App.Api/Models/UserActionRequest.cs index 7f6f2b766..96f6f9245 100644 --- a/src/Altinn.App.Api/Models/UserActionRequest.cs +++ b/src/Altinn.App.Api/Models/UserActionRequest.cs @@ -12,13 +12,13 @@ public class UserActionRequest /// [JsonPropertyName("action")] public string? Action { get; set; } - + /// /// The id of the button that was clicked /// [JsonPropertyName("buttonId")] public string? ButtonId { get; set; } - + /// /// Additional metadata for the action /// diff --git a/src/Altinn.App.Api/Models/UserActionResponse.cs b/src/Altinn.App.Api/Models/UserActionResponse.cs index d0945962f..deef1074a 100644 --- a/src/Altinn.App.Api/Models/UserActionResponse.cs +++ b/src/Altinn.App.Api/Models/UserActionResponse.cs @@ -21,13 +21,13 @@ public class UserActionResponse /// [JsonPropertyName("updatedValidationIssues")] public Dictionary>>? UpdatedValidationIssues { get; set; } - + /// /// Actions the client should perform after action has been performed backend /// [JsonPropertyName("clientActions")] public List? ClientActions { get; set; } - + /// /// Validation issues that occured when processing action /// diff --git a/src/Altinn.App.Core/EFormidling/Extensions/ServiceCollectionExtensions.cs b/src/Altinn.App.Core/EFormidling/Extensions/ServiceCollectionExtensions.cs index 323e33a0f..6b2ba6f08 100644 --- a/src/Altinn.App.Core/EFormidling/Extensions/ServiceCollectionExtensions.cs +++ b/src/Altinn.App.Core/EFormidling/Extensions/ServiceCollectionExtensions.cs @@ -19,11 +19,11 @@ public static class ServiceCollectionExtensions /// The being built. /// A reference to the current object. /// App specific implementation of - public static void AddEFormidlingServices(this IServiceCollection services, IConfiguration configuration) where TM: IEFormidlingMetadata + public static void AddEFormidlingServices(this IServiceCollection services, IConfiguration configuration) where TM : IEFormidlingMetadata { AddEFormidlingServices(services, configuration); } - + /// /// Add Eformidling services and app specific and implementation. /// will not be registered. @@ -32,7 +32,7 @@ public static void AddEFormidlingServices(this IServiceCollection services, /// A reference to the current object. /// App specific implementation of /// App specific implementation of - public static void AddEFormidlingServices(this IServiceCollection services, IConfiguration configuration) where TM: IEFormidlingMetadata where TR: IEFormidlingReceivers + public static void AddEFormidlingServices(this IServiceCollection services, IConfiguration configuration) where TM : IEFormidlingMetadata where TR : IEFormidlingReceivers { services.AddTransient(typeof(IEFormidlingReceivers), typeof(TR)); services.AddHttpClient(); diff --git a/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingReceivers.cs b/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingReceivers.cs index 3ecb0dbe2..6f5b95a07 100644 --- a/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingReceivers.cs +++ b/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingReceivers.cs @@ -25,7 +25,7 @@ public DefaultEFormidlingReceivers(IAppMetadata appMetadata) public async Task> GetEFormidlingReceivers(Instance instance) { await Task.CompletedTask; - + Identifier identifier = new Identifier { // 0192 prefix for all Norwegian organisations. diff --git a/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingService.cs b/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingService.cs index ef4e291b1..b9a236aaf 100644 --- a/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingService.cs +++ b/src/Altinn.App.Core/EFormidling/Implementation/DefaultEFormidlingService.cs @@ -183,7 +183,7 @@ private async Task ConstructStandardBusinessDocument(s private async Task SendInstanceData(Instance instance, Dictionary requestHeaders) { ApplicationMetadata applicationMetadata = await _appMetadata.GetApplicationMetadata(); - + Guid instanceGuid = Guid.Parse(instance.Id.Split("/")[1]); int instanceOwnerPartyId = int.Parse(instance.InstanceOwner.PartyId); foreach (DataElement dataElement in instance.Data) diff --git a/src/Altinn.App.Core/EFormidling/Implementation/EformidlingStatusCheckEventHandler.cs b/src/Altinn.App.Core/EFormidling/Implementation/EformidlingStatusCheckEventHandler.cs index b9fcdcc9d..9c70dcb51 100644 --- a/src/Altinn.App.Core/EFormidling/Implementation/EformidlingStatusCheckEventHandler.cs +++ b/src/Altinn.App.Core/EFormidling/Implementation/EformidlingStatusCheckEventHandler.cs @@ -136,7 +136,7 @@ private async Task ProcessMoveNext(AppIdentifier appIdentifier, InstanceIdentifi /// a logged on user/org. private async Task AddCompleteConfirmation(InstanceIdentifier instanceIdentifier) { - string url = $"instances/{instanceIdentifier.InstanceOwnerPartyId}/{instanceIdentifier.InstanceGuid}/complete"; + string url = $"instances/{instanceIdentifier.InstanceOwnerPartyId}/{instanceIdentifier.InstanceGuid}/complete"; TokenResponse altinnToken = await GetOrganizationToken(); diff --git a/src/Altinn.App.Core/Extensions/HttpClientExtension.cs b/src/Altinn.App.Core/Extensions/HttpClientExtension.cs index 2b892c84d..2c1cf65c6 100644 --- a/src/Altinn.App.Core/Extensions/HttpClientExtension.cs +++ b/src/Altinn.App.Core/Extensions/HttpClientExtension.cs @@ -68,7 +68,7 @@ public static Task GetAsync(this HttpClient httpClient, str return httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None); } - + /// /// Extension that add authorization header to request /// diff --git a/src/Altinn.App.Core/Extensions/ProcessStateExtensions.cs b/src/Altinn.App.Core/Extensions/ProcessStateExtensions.cs index 561e97505..85d6cd037 100644 --- a/src/Altinn.App.Core/Extensions/ProcessStateExtensions.cs +++ b/src/Altinn.App.Core/Extensions/ProcessStateExtensions.cs @@ -35,5 +35,5 @@ public static ProcessState Copy(this ProcessState original) copyOfState.StartEvent = original.StartEvent; return copyOfState; - } + } } \ No newline at end of file diff --git a/src/Altinn.App.Core/Features/Action/SigningUserAction.cs b/src/Altinn.App.Core/Features/Action/SigningUserAction.cs index 6ee1a37be..9b6a765ff 100644 --- a/src/Altinn.App.Core/Features/Action/SigningUserAction.cs +++ b/src/Altinn.App.Core/Features/Action/SigningUserAction.cs @@ -14,7 +14,7 @@ namespace Altinn.App.Core.Features.Action; /// /// Class handling tasks that should happen when action signing is performed. /// -public class SigningUserAction: IUserAction +public class SigningUserAction : IUserAction { private readonly IProcessReader _processReader; private readonly ILogger _logger; @@ -35,7 +35,7 @@ public SigningUserAction(IProcessReader processReader, ILogger public string Id => "sign"; diff --git a/src/Altinn.App.Core/Features/Action/UniqueSignatureAuthorizer.cs b/src/Altinn.App.Core/Features/Action/UniqueSignatureAuthorizer.cs index ff9aef12d..4f1940b2b 100644 --- a/src/Altinn.App.Core/Features/Action/UniqueSignatureAuthorizer.cs +++ b/src/Altinn.App.Core/Features/Action/UniqueSignatureAuthorizer.cs @@ -61,7 +61,7 @@ public async Task AuthorizeAction(UserActionAuthorizerContext context) return true; } - + private async Task GetUserIdFromDataElementContainingSignDocument(AppIdentifier appIdentifier, InstanceIdentifier instanceIdentifier, DataElement dataElement) { await using var data = await _dataClient.GetBinaryData(appIdentifier.Org, appIdentifier.App, instanceIdentifier.InstanceOwnerPartyId, instanceIdentifier.InstanceGuid, Guid.Parse(dataElement.Id)); diff --git a/src/Altinn.App.Core/Features/Action/UserActionAuthorizerContext.cs b/src/Altinn.App.Core/Features/Action/UserActionAuthorizerContext.cs index 145240843..3f1af2950 100644 --- a/src/Altinn.App.Core/Features/Action/UserActionAuthorizerContext.cs +++ b/src/Altinn.App.Core/Features/Action/UserActionAuthorizerContext.cs @@ -22,7 +22,7 @@ public UserActionAuthorizerContext(ClaimsPrincipal user, InstanceIdentifier inst TaskId = taskId; Action = action; } - + /// /// Gets or sets the user /// diff --git a/src/Altinn.App.Core/Features/DataLists/NullInstanceDataListProvider.cs b/src/Altinn.App.Core/Features/DataLists/NullInstanceDataListProvider.cs index 8fb337190..059e2187e 100644 --- a/src/Altinn.App.Core/Features/DataLists/NullInstanceDataListProvider.cs +++ b/src/Altinn.App.Core/Features/DataLists/NullInstanceDataListProvider.cs @@ -12,7 +12,7 @@ namespace Altinn.App.Core.Features.DataLists /// ListIttems is set to null and not an empty list for the controller to be able to differensiate /// between option provider found, but with no values and no option provider found ie. returns 404. /// - public class NullInstanceDataListProvider: IInstanceDataListProvider + public class NullInstanceDataListProvider : IInstanceDataListProvider { /// public string Id => string.Empty; diff --git a/src/Altinn.App.Core/Features/DataProcessing/NullInstantiationProcessor.cs b/src/Altinn.App.Core/Features/DataProcessing/NullInstantiationProcessor.cs index e6e99dac7..994bfd198 100644 --- a/src/Altinn.App.Core/Features/DataProcessing/NullInstantiationProcessor.cs +++ b/src/Altinn.App.Core/Features/DataProcessing/NullInstantiationProcessor.cs @@ -6,7 +6,7 @@ namespace Altinn.App.Core.Features.DataProcessing; /// Default implementation of the IInstantiationProcessor interface. /// This implementation does not do any thing to the data /// -public class NullInstantiationProcessor: IInstantiationProcessor +public class NullInstantiationProcessor : IInstantiationProcessor { /// public async Task DataCreation(Instance instance, object data, Dictionary? prefill) diff --git a/src/Altinn.App.Core/Features/FileAnalyzis/FileAnalysisResult.cs b/src/Altinn.App.Core/Features/FileAnalyzis/FileAnalysisResult.cs index 279cd97d3..3f9eb34a5 100644 --- a/src/Altinn.App.Core/Features/FileAnalyzis/FileAnalysisResult.cs +++ b/src/Altinn.App.Core/Features/FileAnalyzis/FileAnalysisResult.cs @@ -35,10 +35,10 @@ public FileAnalysisResult(string analyserId) /// The mime type /// public string? MimeType { get; set; } - + /// /// Key/Value pairs containing findings from the analysis. /// - public IDictionary Metadata { get; private set; } = new Dictionary(); + public IDictionary Metadata { get; private set; } = new Dictionary(); } } diff --git a/src/Altinn.App.Core/Features/IInstanceValidator.cs b/src/Altinn.App.Core/Features/IInstanceValidator.cs index 956d0aaeb..38f5e24cf 100644 --- a/src/Altinn.App.Core/Features/IInstanceValidator.cs +++ b/src/Altinn.App.Core/Features/IInstanceValidator.cs @@ -17,7 +17,7 @@ public interface IInstanceValidator /// Object containing any validation errors/warnings /// Task to indicate when validation is completed public Task ValidateData(object data, ModelStateDictionary validationResults); - + /// /// Is called to run custom task validation events. /// diff --git a/src/Altinn.App.Core/Features/IProcessTaskEnd.cs b/src/Altinn.App.Core/Features/IProcessTaskEnd.cs index e70761305..efa89d3f0 100644 --- a/src/Altinn.App.Core/Features/IProcessTaskEnd.cs +++ b/src/Altinn.App.Core/Features/IProcessTaskEnd.cs @@ -12,5 +12,5 @@ public interface IProcessTaskEnd /// /// The taskId /// The instance - public Task End(string taskId, Instance instance); + public Task End(string taskId, Instance instance); } diff --git a/src/Altinn.App.Core/Features/IProcessTaskStart.cs b/src/Altinn.App.Core/Features/IProcessTaskStart.cs index ea7c88d68..ed6f76f0c 100644 --- a/src/Altinn.App.Core/Features/IProcessTaskStart.cs +++ b/src/Altinn.App.Core/Features/IProcessTaskStart.cs @@ -13,5 +13,5 @@ public interface IProcessTaskStart /// The taskId /// The instance /// Prefill data - public Task Start(string taskId, Instance instance, Dictionary prefill); + public Task Start(string taskId, Instance instance, Dictionary prefill); } diff --git a/src/Altinn.App.Core/Features/IUserAction.cs b/src/Altinn.App.Core/Features/IUserAction.cs index 9b39a3368..50eb8a125 100644 --- a/src/Altinn.App.Core/Features/IUserAction.cs +++ b/src/Altinn.App.Core/Features/IUserAction.cs @@ -11,7 +11,7 @@ public interface IUserAction /// The id of the user action /// string Id { get; } - + /// /// Method for handling the user action /// diff --git a/src/Altinn.App.Core/Features/Options/Altinn2Provider/Altinn2CodeListProvider.cs b/src/Altinn.App.Core/Features/Options/Altinn2Provider/Altinn2CodeListProvider.cs index f38db25c7..3a09abadc 100644 --- a/src/Altinn.App.Core/Features/Options/Altinn2Provider/Altinn2CodeListProvider.cs +++ b/src/Altinn.App.Core/Features/Options/Altinn2Provider/Altinn2CodeListProvider.cs @@ -39,7 +39,7 @@ public class Altinn2CodeListProvider : IAppOptionsProvider private readonly IMemoryCache _cache; /// - public string Id { get; private set; } + public string Id { get; private set; } /// /// diff --git a/src/Altinn.App.Core/Features/Options/Altinn2Provider/Altinn2MetadataApiClient.cs b/src/Altinn.App.Core/Features/Options/Altinn2Provider/Altinn2MetadataApiClient.cs index 86fb11ac3..e02469f5b 100644 --- a/src/Altinn.App.Core/Features/Options/Altinn2Provider/Altinn2MetadataApiClient.cs +++ b/src/Altinn.App.Core/Features/Options/Altinn2Provider/Altinn2MetadataApiClient.cs @@ -29,7 +29,7 @@ public Altinn2MetadataApiClient(HttpClient client) public async Task GetAltinn2Codelist(string id, string langCode, int? version = null) { var response = await _client.GetAsync($"https://www.altinn.no/api/metadata/codelists/{id}/{version?.ToString() ?? string.Empty}?language={langCode}"); - if(response.StatusCode == System.Net.HttpStatusCode.NotFound) + if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { response = await _client.GetAsync($"https://www.altinn.no/api/metadata/codelists/{id}/{version?.ToString() ?? string.Empty}"); } diff --git a/src/Altinn.App.Core/Features/Options/DefaultAppOptionsProvider.cs b/src/Altinn.App.Core/Features/Options/DefaultAppOptionsProvider.cs index 571719a7b..29870a3a3 100644 --- a/src/Altinn.App.Core/Features/Options/DefaultAppOptionsProvider.cs +++ b/src/Altinn.App.Core/Features/Options/DefaultAppOptionsProvider.cs @@ -6,7 +6,7 @@ namespace Altinn.App.Core.Features.Options public class DefaultAppOptionsProvider : IAppOptionsProvider { private readonly IAppOptionsFileHandler _appOptionsFileHandler; - + /// /// Initializes a new instance of the class. /// diff --git a/src/Altinn.App.Core/Features/Validation/Default/DefaultDataElementValidator.cs b/src/Altinn.App.Core/Features/Validation/Default/DefaultDataElementValidator.cs index 9666ddea2..6c9d11d28 100644 --- a/src/Altinn.App.Core/Features/Validation/Default/DefaultDataElementValidator.cs +++ b/src/Altinn.App.Core/Features/Validation/Default/DefaultDataElementValidator.cs @@ -20,7 +20,7 @@ public Task> ValidateDataElement(Instance instance, DataEl var issues = new List(); if (dataElement.ContentType == null) { - issues.Add( new ValidationIssue + issues.Add(new ValidationIssue { Code = ValidationIssueCodes.DataElementCodes.MissingContentType, DataElementId = dataElement.Id, @@ -36,7 +36,7 @@ public Task> ValidateDataElement(Instance instance, DataEl dataType.AllowedContentTypes.TrueForAll(ct => !ct.Equals(contentTypeWithoutEncoding, StringComparison.OrdinalIgnoreCase))) { - issues.Add( new ValidationIssue + issues.Add(new ValidationIssue { DataElementId = dataElement.Id, Code = ValidationIssueCodes.DataElementCodes.ContentTypeNotAllowed, @@ -50,7 +50,7 @@ public Task> ValidateDataElement(Instance instance, DataEl if (dataType.MaxSize.HasValue && dataType.MaxSize > 0 && (long)dataType.MaxSize * 1024 * 1024 < dataElement.Size) { - issues.Add( new ValidationIssue + issues.Add(new ValidationIssue { DataElementId = dataElement.Id, Code = ValidationIssueCodes.DataElementCodes.DataElementTooLarge, @@ -62,7 +62,7 @@ public Task> ValidateDataElement(Instance instance, DataEl if (dataType.EnableFileScan && dataElement.FileScanResult == FileScanResult.Infected) { - issues.Add( new ValidationIssue + issues.Add(new ValidationIssue { DataElementId = dataElement.Id, Code = ValidationIssueCodes.DataElementCodes.DataElementFileInfected, @@ -75,7 +75,7 @@ public Task> ValidateDataElement(Instance instance, DataEl if (dataType.EnableFileScan && dataType.ValidationErrorOnPendingFileScan && dataElement.FileScanResult == FileScanResult.Pending) { - issues.Add( new ValidationIssue + issues.Add(new ValidationIssue { DataElementId = dataElement.Id, Code = ValidationIssueCodes.DataElementCodes.DataElementFileScanPending, diff --git a/src/Altinn.App.Core/Features/Validation/Default/RequiredValidator.cs b/src/Altinn.App.Core/Features/Validation/Default/RequiredValidator.cs index b145dfa18..a2182061c 100644 --- a/src/Altinn.App.Core/Features/Validation/Default/RequiredValidator.cs +++ b/src/Altinn.App.Core/Features/Validation/Default/RequiredValidator.cs @@ -45,7 +45,7 @@ public RequiredLayoutValidator(LayoutEvaluatorStateInitializer layoutEvaluatorSt public async Task> ValidateFormData(Instance instance, DataElement dataElement, object data, string? language) { var appMetadata = await _appMetadata.GetApplicationMetadata(); - var layoutSet = _appResourcesService.GetLayoutSetForTask(appMetadata.DataTypes.First(dt=>dt.Id == dataElement.DataType).TaskId); + var layoutSet = _appResourcesService.GetLayoutSetForTask(appMetadata.DataTypes.First(dt => dt.Id == dataElement.DataType).TaskId); var evaluationState = await _layoutEvaluatorStateInitializer.Init(instance, data, layoutSet?.Id); return LayoutEvaluator.RunLayoutValidationsForRequired(evaluationState, dataElement.Id); } diff --git a/src/Altinn.App.Core/Features/Validation/GenericFormDataValidator.cs b/src/Altinn.App.Core/Features/Validation/GenericFormDataValidator.cs index 3da004696..6fd2fbdea 100644 --- a/src/Altinn.App.Core/Features/Validation/GenericFormDataValidator.cs +++ b/src/Altinn.App.Core/Features/Validation/GenericFormDataValidator.cs @@ -54,7 +54,7 @@ public bool HasRelevantChanges(object current, object previous) /// Optional description if you want to provide a user friendly message that don't rely on the translation system /// optional short code for the type of issue /// List of parameters to replace after looking up the translation. Zero indexed {0} - protected void CreateValidationIssue(Expression> selector, string textKey, ValidationIssueSeverity severity = ValidationIssueSeverity.Error, string? description = null, string? code = null, List? customTextParams = null) + protected void CreateValidationIssue(Expression> selector, string textKey, ValidationIssueSeverity severity = ValidationIssueSeverity.Error, string? description = null, string? code = null, List? customTextParams = null) { Debug.Assert(ValidationIssues.Value is not null); AddValidationIssue(new ValidationIssue diff --git a/src/Altinn.App.Core/Features/Validation/Helpers/ModelStateHelpers.cs b/src/Altinn.App.Core/Features/Validation/Helpers/ModelStateHelpers.cs index 5979663e9..5ec2df2cc 100644 --- a/src/Altinn.App.Core/Features/Validation/Helpers/ModelStateHelpers.cs +++ b/src/Altinn.App.Core/Features/Validation/Helpers/ModelStateHelpers.cs @@ -101,7 +101,7 @@ private static (ValidationIssueSeverity Severity, string Message) GetSeverityFro var rest = keyParts?.ElementAtOrDefault(1); var properties = data?.GetProperties(); - var property = properties is not null ? Array.Find(properties,p => p.Name == key) : null; + var property = properties is not null ? Array.Find(properties, p => p.Name == key) : null; var jsonPropertyName = property ?.GetCustomAttributes(true) .OfType() diff --git a/src/Altinn.App.Core/Features/Validation/NullInstantiationValidator.cs b/src/Altinn.App.Core/Features/Validation/NullInstantiationValidator.cs index 4152cab23..deea74222 100644 --- a/src/Altinn.App.Core/Features/Validation/NullInstantiationValidator.cs +++ b/src/Altinn.App.Core/Features/Validation/NullInstantiationValidator.cs @@ -7,7 +7,7 @@ namespace Altinn.App.Core.Features.Validation; /// Default implementation of the IInstantiationValidator interface. /// This implementation does not do any thing to the data /// -public class NullInstantiationValidator: IInstantiationValidator +public class NullInstantiationValidator : IInstantiationValidator { /// public async Task Validate(Instance instance) diff --git a/src/Altinn.App.Core/Helpers/DataModel/DataModelException.cs b/src/Altinn.App.Core/Helpers/DataModel/DataModelException.cs index 6aa37e379..600ab6f53 100644 --- a/src/Altinn.App.Core/Helpers/DataModel/DataModelException.cs +++ b/src/Altinn.App.Core/Helpers/DataModel/DataModelException.cs @@ -8,5 +8,5 @@ namespace Altinn.App.Core.Helpers.DataModel; public class DataModelException : Exception { /// - public DataModelException(string msg): base(msg) { } + public DataModelException(string msg) : base(msg) { } } \ No newline at end of file diff --git a/src/Altinn.App.Core/Helpers/MultiDecisionHelper.cs b/src/Altinn.App.Core/Helpers/MultiDecisionHelper.cs index 931393556..6e4b64d31 100644 --- a/src/Altinn.App.Core/Helpers/MultiDecisionHelper.cs +++ b/src/Altinn.App.Core/Helpers/MultiDecisionHelper.cs @@ -42,7 +42,7 @@ public static XacmlJsonRequestRoot CreateMultiDecisionRequest(ClaimsPrincipal us return jsonRequest; } - + /// /// Validate a multi decision result and returns a dictionary with the actions and the result. /// @@ -181,5 +181,5 @@ private static List CreateRequestReference(List RemoveBom(this byte[] bytes) { return bytes.AsSpan().Slice(_utf8bom.Length); } - + return bytes; } } \ No newline at end of file diff --git a/src/Altinn.App.Core/Helpers/ServiceException.cs b/src/Altinn.App.Core/Helpers/ServiceException.cs index 04bfc1e3b..bd39d9988 100644 --- a/src/Altinn.App.Core/Helpers/ServiceException.cs +++ b/src/Altinn.App.Core/Helpers/ServiceException.cs @@ -11,7 +11,7 @@ public class ServiceException : Exception /// /// The proposed return http status code. /// - public HttpStatusCode StatusCode { get; } + public HttpStatusCode StatusCode { get; } /// /// Add a proposed http status return code and message. diff --git a/src/Altinn.App.Core/Implementation/DefaultAppEvents.cs b/src/Altinn.App.Core/Implementation/DefaultAppEvents.cs index 4406e7d7d..d6eb5ef54 100644 --- a/src/Altinn.App.Core/Implementation/DefaultAppEvents.cs +++ b/src/Altinn.App.Core/Implementation/DefaultAppEvents.cs @@ -10,7 +10,7 @@ namespace Altinn.App.Core.Implementation; /// /// Default handling of instance events /// -public class DefaultAppEvents: IAppEvents +public class DefaultAppEvents : IAppEvents { private readonly ILogger _logger; private readonly IAppMetadata _appMetadata; @@ -21,8 +21,8 @@ public class DefaultAppEvents: IAppEvents /// Constructor with services from DI /// public DefaultAppEvents( - ILogger logger, - IAppMetadata appMetadata, + ILogger logger, + IAppMetadata appMetadata, IInstanceClient instanceClient, IDataClient dataClient) { @@ -30,7 +30,7 @@ public DefaultAppEvents( _appMetadata = appMetadata; _instanceClient = instanceClient; _dataClient = dataClient; - + } /// @@ -46,7 +46,7 @@ public async Task OnEndAppEvent(string endEvent, Instance instance) _logger.LogInformation("OnEndProcess for {Id}, endEvent: {EndEvent}", instance.Id, endEvent); } - + private async Task AutoDeleteDataElements(Instance instance) { ApplicationMetadata applicationMetadata = await _appMetadata.GetApplicationMetadata(); @@ -56,7 +56,7 @@ private async Task AutoDeleteDataElements(Instance instance) { return; } - + instance = await _instanceClient.GetInstance(instance); List elementsToDelete = instance.Data.Where(e => typesToDelete.Contains(e.DataType)).ToList(); diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Authorization/AuthorizationClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/Authorization/AuthorizationClient.cs index dd3906a51..47bd4e50a 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Authorization/AuthorizationClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Authorization/AuthorizationClient.cs @@ -137,6 +137,6 @@ public async Task> AuthorizeActions(Instance instance, return MultiDecisionHelper.ValidatePdpMultiDecision(actionsResult, response.Response, user); } - + } } diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Events/EventsSubscriptionClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/Events/EventsSubscriptionClient.cs index 7ade4288a..edfa3bd10 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Events/EventsSubscriptionClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Events/EventsSubscriptionClient.cs @@ -25,9 +25,9 @@ public class EventsSubscriptionClient : IEventsSubscription /// Initializes a new instance of the class. /// public EventsSubscriptionClient( - IOptions platformSettings, - HttpClient httpClient, - IOptions generalSettings, + IOptions platformSettings, + HttpClient httpClient, + IOptions generalSettings, IEventSecretCodeProvider secretCodeProvider, ILogger logger) { @@ -64,7 +64,7 @@ public async Task AddSubscription(string org, string app, string e _logger.LogInformation("About to send the following subscription request {subscriptionJson}", serializedSubscriptionRequest); HttpResponseMessage response = await _client.PostAsync( - "subscriptions", + "subscriptions", new StringContent(serializedSubscriptionRequest, Encoding.UTF8, "application/json")); if (response.IsSuccessStatusCode) diff --git a/src/Altinn.App.Core/Infrastructure/Clients/KeyVault/SecretsLocalClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/KeyVault/SecretsLocalClient.cs index 7d5b5d0ac..fef53bff5 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/KeyVault/SecretsLocalClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/KeyVault/SecretsLocalClient.cs @@ -52,7 +52,7 @@ public async Task GetSecretAsync(string secretId) } private string GetTokenFromSecrets(string secretId) - => GetTokenFromLocalSecrets(secretId) ?? + => GetTokenFromLocalSecrets(secretId) ?? GetTokenFromConfiguration(secretId) ?? throw new ArgumentException($"SecretId={secretId} does not exist in appsettings or secrets.json"); diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Register/RegisterERClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/Register/RegisterERClient.cs index 6e1ca9048..426a19f1d 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Register/RegisterERClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Register/RegisterERClient.cs @@ -43,7 +43,7 @@ public RegisterERClient( IHttpContextAccessor httpContextAccessor, IOptionsMonitor settings, HttpClient httpClient, - IAccessTokenGenerator accessTokenGenerator, + IAccessTokenGenerator accessTokenGenerator, IAppMetadata appMetadata) { _logger = logger; diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Storage/DataClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/Storage/DataClient.cs index d72dd04bc..2dac8160b 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Storage/DataClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Storage/DataClient.cs @@ -42,7 +42,7 @@ public class DataClient : IDataClient public DataClient( IOptions platformSettings, ILogger logger, - HttpClient httpClient, + HttpClient httpClient, IUserTokenProvider userTokenProvider) { _platformSettings = platformSettings.Value; @@ -73,7 +73,7 @@ public async Task InsertFormData(Instance instance, string dataT string apiUrl = $"instances/{instance.Id}/data?dataType={dataType}"; string token = _userTokenProvider.GetUserToken(); DataElement dataElement; - + using MemoryStream stream = new MemoryStream(); Serialize(dataToSerialize, type, stream); @@ -102,7 +102,7 @@ public async Task UpdateData(T dataToSerialize, Guid instanceGui string token = _userTokenProvider.GetUserToken(); using MemoryStream stream = new MemoryStream(); - + Serialize(dataToSerialize, type, stream); stream.Position = 0; @@ -294,7 +294,7 @@ public async Task InsertBinaryData(string org, string app, int inst public async Task InsertBinaryData(string instanceId, string dataType, string contentType, string? filename, Stream stream, string? generatedFromTask = null) { string apiUrl = $"{_platformSettings.ApiStorageEndpoint}instances/{instanceId}/data?dataType={dataType}"; - if(!string.IsNullOrEmpty(generatedFromTask)) + if (!string.IsNullOrEmpty(generatedFromTask)) { apiUrl += $"&generatedFromTask={generatedFromTask}"; } @@ -348,7 +348,7 @@ public async Task UpdateBinaryData(string org, string app, int inst _logger.LogError($"Updating attachment {dataGuid} for instance {instanceGuid} failed with status code {response.StatusCode}"); throw await PlatformHttpException.CreateAsync(response); } - + /// public async Task UpdateBinaryData(InstanceIdentifier instanceIdentifier, string? contentType, string filename, Guid dataGuid, Stream stream) { diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceClientMetricsDecorator.cs b/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceClientMetricsDecorator.cs index a9d85ec54..9b1d70c85 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceClientMetricsDecorator.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Storage/InstanceClientMetricsDecorator.cs @@ -14,7 +14,7 @@ public class InstanceClientMetricsDecorator : IInstanceClient private readonly IInstanceClient _instanceClient; private static readonly Counter InstancesCreatedCounter = Metrics.CreateCounter("altinn_app_instances_created", "Number of instances created", "result"); private static readonly Counter InstancesCompletedCounter = Metrics.CreateCounter("altinn_app_instances_completed", "Number of instances completed", "result"); - private static readonly Counter InstancesDeletedCounter = Metrics.CreateCounter("altinn_app_instances_deleted", "Number of instances completed", "result", "mode" ); + private static readonly Counter InstancesDeletedCounter = Metrics.CreateCounter("altinn_app_instances_deleted", "Number of instances completed", "result", "mode"); /// /// Create a new instance of the class. diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Storage/ProcessClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/Storage/ProcessClient.cs index 97424abe7..e14b44d33 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Storage/ProcessClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Storage/ProcessClient.cs @@ -46,7 +46,7 @@ public ProcessClient( /// public Stream GetProcessDefinition() { - string bpmnFilePath = Path.Join(_appSettings.AppBasePath , _appSettings.ConfigurationFolder , _appSettings.ProcessFolder , _appSettings.ProcessFileName); + string bpmnFilePath = Path.Join(_appSettings.AppBasePath, _appSettings.ConfigurationFolder, _appSettings.ProcessFolder, _appSettings.ProcessFileName); try { diff --git a/src/Altinn.App.Core/Infrastructure/Clients/Storage/SignClient.cs b/src/Altinn.App.Core/Infrastructure/Clients/Storage/SignClient.cs index 227a04833..e347ae101 100644 --- a/src/Altinn.App.Core/Infrastructure/Clients/Storage/SignClient.cs +++ b/src/Altinn.App.Core/Infrastructure/Clients/Storage/SignClient.cs @@ -14,11 +14,11 @@ namespace Altinn.App.Core.Infrastructure.Clients.Storage /// /// Implementation of that sends signing requests to platform /// - public class SignClient: ISignClient + public class SignClient : ISignClient { private readonly IUserTokenProvider _userTokenProvider; private readonly HttpClient _client; - + /// /// Create a new instance of /// @@ -27,7 +27,7 @@ public class SignClient: ISignClient /// Service that can provide user token public SignClient( IOptions platformSettings, - HttpClient httpClient, + HttpClient httpClient, IUserTokenProvider userTokenProvider) { var platformSettings1 = platformSettings.Value; @@ -39,7 +39,7 @@ public SignClient( _client = httpClient; _userTokenProvider = userTokenProvider; } - + /// public async Task SignDataElements(SignatureContext signatureContext) { @@ -50,7 +50,7 @@ public async Task SignDataElements(SignatureContext signatureContext) { return; } - + throw new PlatformHttpException(response, "Failed to sign dataelements"); } diff --git a/src/Altinn.App.Core/Interface/IAppEvents.cs b/src/Altinn.App.Core/Interface/IAppEvents.cs index 9db8e3186..fdb7d140e 100644 --- a/src/Altinn.App.Core/Interface/IAppEvents.cs +++ b/src/Altinn.App.Core/Interface/IAppEvents.cs @@ -15,7 +15,7 @@ public interface IAppEvents /// Instance data /// public Task OnStartAppEvent(string startEvent, Instance instance); - + /// /// Is called when the process for an instance is ended. /// diff --git a/src/Altinn.App.Core/Interface/IData.cs b/src/Altinn.App.Core/Interface/IData.cs index 742c5f6b2..6ac43717c 100644 --- a/src/Altinn.App.Core/Interface/IData.cs +++ b/src/Altinn.App.Core/Interface/IData.cs @@ -120,7 +120,7 @@ public interface IData /// The instance id /// The data id /// Http request containing the attachment to be saved - [Obsolete(message:"Deprecated please use UpdateBinaryData(InstanceIdentifier, string, string, Guid, Stream) instead", error: false)] + [Obsolete(message: "Deprecated please use UpdateBinaryData(InstanceIdentifier, string, string, Guid, Stream) instead", error: false)] Task UpdateBinaryData(string org, string app, int instanceOwnerPartyId, Guid instanceGuid, Guid dataGuid, HttpRequest request); /// diff --git a/src/Altinn.App.Core/Interface/IInstance.cs b/src/Altinn.App.Core/Interface/IInstance.cs index 46b5245b4..c730032af 100644 --- a/src/Altinn.App.Core/Interface/IInstance.cs +++ b/src/Altinn.App.Core/Interface/IInstance.cs @@ -106,7 +106,7 @@ public interface IInstance async Task UpdateDataValues(Instance instance, Dictionary dataValues) { var id = new InstanceIdentifier(instance); - return await UpdateDataValues(id.InstanceOwnerPartyId, id.InstanceGuid, new DataValues{Values = dataValues}); + return await UpdateDataValues(id.InstanceOwnerPartyId, id.InstanceGuid, new DataValues { Values = dataValues }); } /// @@ -121,7 +121,7 @@ async Task UpdateDataValues(Instance instance, DictionaryReturns the updated instance. async Task UpdateDataValue(Instance instance, string key, string? value) { - return await UpdateDataValues(instance, new Dictionary{{key, value}}); + return await UpdateDataValues(instance, new Dictionary { { key, value } }); } /// diff --git a/src/Altinn.App.Core/Interface/ITaskEvents.cs b/src/Altinn.App.Core/Interface/ITaskEvents.cs index 0af8bb45a..674df5685 100644 --- a/src/Altinn.App.Core/Interface/ITaskEvents.cs +++ b/src/Altinn.App.Core/Interface/ITaskEvents.cs @@ -16,7 +16,7 @@ public interface ITaskEvents /// Prefill data /// public Task OnStartProcessTask(string taskId, Instance instance, Dictionary prefill); - + /// /// Is called after the process task is ended. Method can update instance and data element metadata. /// @@ -24,12 +24,12 @@ public interface ITaskEvents /// Instance data /// public Task OnEndProcessTask(string endEvent, Instance instance); - + /// /// Is called after the process task is abonded. Method can update instance and data element metadata. /// /// task id of task to abandon /// Instance data public Task OnAbandonProcessTask(string taskId, Instance instance); - + } diff --git a/src/Altinn.App.Core/Internal/App/AppMetadata.cs b/src/Altinn.App.Core/Internal/App/AppMetadata.cs index 71fb4def8..08bee7d50 100644 --- a/src/Altinn.App.Core/Internal/App/AppMetadata.cs +++ b/src/Altinn.App.Core/Internal/App/AppMetadata.cs @@ -56,7 +56,7 @@ public async Task GetApplicationMetadata() { throw new ApplicationConfigException($"Deserialization returned null, Could indicate problems with deserialization of {filename}"); } - + application.Features = await _frontendFeatures.GetFrontendFeatures(); _application = application; diff --git a/src/Altinn.App.Core/Internal/App/ApplicationConfigException.cs b/src/Altinn.App.Core/Internal/App/ApplicationConfigException.cs index e04d91078..5d89cef4d 100644 --- a/src/Altinn.App.Core/Internal/App/ApplicationConfigException.cs +++ b/src/Altinn.App.Core/Internal/App/ApplicationConfigException.cs @@ -5,7 +5,7 @@ namespace Altinn.App.Core.Internal.App /// /// Configuration is not valid for application /// - public class ApplicationConfigException: Exception + public class ApplicationConfigException : Exception { /// diff --git a/src/Altinn.App.Core/Internal/App/IAppEvents.cs b/src/Altinn.App.Core/Internal/App/IAppEvents.cs index 4ca2cb84b..d41a2bd3f 100644 --- a/src/Altinn.App.Core/Internal/App/IAppEvents.cs +++ b/src/Altinn.App.Core/Internal/App/IAppEvents.cs @@ -14,7 +14,7 @@ public interface IAppEvents /// Instance data /// public Task OnStartAppEvent(string startEvent, Instance instance); - + /// /// Is called when the process for an instance is ended. /// diff --git a/src/Altinn.App.Core/Internal/App/IAppMetadata.cs b/src/Altinn.App.Core/Internal/App/IAppMetadata.cs index 36582ba27..fd12f3814 100644 --- a/src/Altinn.App.Core/Internal/App/IAppMetadata.cs +++ b/src/Altinn.App.Core/Internal/App/IAppMetadata.cs @@ -13,14 +13,14 @@ public interface IAppMetadata /// /// public Task GetApplicationMetadata(); - + /// /// Returns the application XACML policy for an application. /// /// The application XACML policy for an application. /// public Task GetApplicationXACMLPolicy(); - + /// /// Returns the application BPMN process for an application. /// diff --git a/src/Altinn.App.Core/Internal/AppModel/DefaultAppModel.cs b/src/Altinn.App.Core/Internal/AppModel/DefaultAppModel.cs index 9dc88beea..b3b23b54b 100644 --- a/src/Altinn.App.Core/Internal/AppModel/DefaultAppModel.cs +++ b/src/Altinn.App.Core/Internal/AppModel/DefaultAppModel.cs @@ -4,10 +4,10 @@ namespace Altinn.App.Core.Internal.AppModel; /// -public class DefaultAppModel: IAppModel +public class DefaultAppModel : IAppModel { private readonly ILogger _logger; - + /// /// Create with services from Dependency Injcection /// @@ -15,7 +15,7 @@ public DefaultAppModel(ILogger logger) { _logger = logger; } - + /// public object Create(string classRef) { diff --git a/src/Altinn.App.Core/Internal/Auth/AuthorizationService.cs b/src/Altinn.App.Core/Internal/Auth/AuthorizationService.cs index c76e0af62..508393797 100644 --- a/src/Altinn.App.Core/Internal/Auth/AuthorizationService.cs +++ b/src/Altinn.App.Core/Internal/Auth/AuthorizationService.cs @@ -69,11 +69,11 @@ public async Task> AuthorizeActions(Instance instance, ClaimsPr { authorizedActions.Add(new UserAction() { - Id = action.Value, - Authorized = authDecisions[action.Value], - ActionType = action.ActionType + Id = action.Value, + Authorized = authDecisions[action.Value], + ActionType = action.ActionType }); - + } return authorizedActions; diff --git a/src/Altinn.App.Core/Internal/Auth/IAuthorizationClient.cs b/src/Altinn.App.Core/Internal/Auth/IAuthorizationClient.cs index 41fc248bd..7f4d3fdb3 100644 --- a/src/Altinn.App.Core/Internal/Auth/IAuthorizationClient.cs +++ b/src/Altinn.App.Core/Internal/Auth/IAuthorizationClient.cs @@ -37,7 +37,7 @@ public interface IAuthorizationClient /// /// Task AuthorizeAction(AppIdentifier appIdentifier, InstanceIdentifier instanceIdentifier, ClaimsPrincipal user, string action, string? taskId = null); - + /// /// Check if the user is authorized to perform the given actions on the given instance. /// diff --git a/src/Altinn.App.Core/Internal/Auth/IAuthorizationService.cs b/src/Altinn.App.Core/Internal/Auth/IAuthorizationService.cs index 852467a7c..a04251c06 100644 --- a/src/Altinn.App.Core/Internal/Auth/IAuthorizationService.cs +++ b/src/Altinn.App.Core/Internal/Auth/IAuthorizationService.cs @@ -37,7 +37,7 @@ public interface IAuthorizationService /// /// Task AuthorizeAction(AppIdentifier appIdentifier, InstanceIdentifier instanceIdentifier, ClaimsPrincipal user, string action, string? taskId = null); - + /// /// Check if the user is authorized to perform the given actions on the given instance. /// diff --git a/src/Altinn.App.Core/Internal/Data/IDataClient.cs b/src/Altinn.App.Core/Internal/Data/IDataClient.cs index 61f361e19..8f50cef0e 100644 --- a/src/Altinn.App.Core/Internal/Data/IDataClient.cs +++ b/src/Altinn.App.Core/Internal/Data/IDataClient.cs @@ -119,7 +119,7 @@ public interface IDataClient /// The instance id /// The data id /// Http request containing the attachment to be saved - [Obsolete(message:"Deprecated please use UpdateBinaryData(InstanceIdentifier, string, string, Guid, Stream) instead", error: false)] + [Obsolete(message: "Deprecated please use UpdateBinaryData(InstanceIdentifier, string, string, Guid, Stream) instead", error: false)] Task UpdateBinaryData(string org, string app, int instanceOwnerPartyId, Guid instanceGuid, Guid dataGuid, HttpRequest request); /// @@ -151,7 +151,7 @@ public interface IDataClient /// The data element with values to update /// the updated data element Task Update(Instance instance, DataElement dataElement); - + /// /// Lock data element in storage /// @@ -159,7 +159,7 @@ public interface IDataClient /// Id of the DataElement to lock /// Task LockDataElement(InstanceIdentifier instanceIdentifier, Guid dataGuid); - + /// /// Unlock data element in storage /// diff --git a/src/Altinn.App.Core/Internal/Events/SubscriptionValidationHandler.cs b/src/Altinn.App.Core/Internal/Events/SubscriptionValidationHandler.cs index 9367b319e..c1536f109 100644 --- a/src/Altinn.App.Core/Internal/Events/SubscriptionValidationHandler.cs +++ b/src/Altinn.App.Core/Internal/Events/SubscriptionValidationHandler.cs @@ -15,7 +15,7 @@ public class SubscriptionValidationHandler : IEventHandler /// public Task ProcessEvent(CloudEvent cloudEvent) { - return Task.FromResult(true); + return Task.FromResult(true); } } } \ No newline at end of file diff --git a/src/Altinn.App.Core/Internal/Expressions/ExpressionEvaluatorTypeErrorException.cs b/src/Altinn.App.Core/Internal/Expressions/ExpressionEvaluatorTypeErrorException.cs index bcb87bc3e..71f7ce5ea 100644 --- a/src/Altinn.App.Core/Internal/Expressions/ExpressionEvaluatorTypeErrorException.cs +++ b/src/Altinn.App.Core/Internal/Expressions/ExpressionEvaluatorTypeErrorException.cs @@ -8,7 +8,7 @@ namespace Altinn.App.Core.Internal.Expressions; public class ExpressionEvaluatorTypeErrorException : Exception { /// - public ExpressionEvaluatorTypeErrorException(string msg) : base(msg) {} + public ExpressionEvaluatorTypeErrorException(string msg) : base(msg) { } /// - public ExpressionEvaluatorTypeErrorException(string msg, Exception innerException) : base(msg, innerException) {} + public ExpressionEvaluatorTypeErrorException(string msg, Exception innerException) : base(msg, innerException) { } } \ No newline at end of file diff --git a/src/Altinn.App.Core/Internal/Instances/IInstanceClient.cs b/src/Altinn.App.Core/Internal/Instances/IInstanceClient.cs index e64640bb7..d7afa5c2b 100644 --- a/src/Altinn.App.Core/Internal/Instances/IInstanceClient.cs +++ b/src/Altinn.App.Core/Internal/Instances/IInstanceClient.cs @@ -105,7 +105,7 @@ public interface IInstanceClient async Task UpdateDataValues(Instance instance, Dictionary dataValues) { var id = new InstanceIdentifier(instance); - return await UpdateDataValues(id.InstanceOwnerPartyId, id.InstanceGuid, new DataValues{Values = dataValues}); + return await UpdateDataValues(id.InstanceOwnerPartyId, id.InstanceGuid, new DataValues { Values = dataValues }); } /// @@ -120,7 +120,7 @@ async Task UpdateDataValues(Instance instance, DictionaryReturns the updated instance. async Task UpdateDataValue(Instance instance, string key, string? value) { - return await UpdateDataValues(instance, new Dictionary{{key, value}}); + return await UpdateDataValues(instance, new Dictionary { { key, value } }); } /// diff --git a/src/Altinn.App.Core/Internal/Patch/DataPatchError.cs b/src/Altinn.App.Core/Internal/Patch/DataPatchError.cs index f476e89e7..6d86958a9 100644 --- a/src/Altinn.App.Core/Internal/Patch/DataPatchError.cs +++ b/src/Altinn.App.Core/Internal/Patch/DataPatchError.cs @@ -17,7 +17,7 @@ public class DataPatchError /// The type of error that occurred. /// public DataPatchErrorType? ErrorType { get; set; } - + /// /// Additional information about the error. /// diff --git a/src/Altinn.App.Core/Internal/Pdf/PdfService.cs b/src/Altinn.App.Core/Internal/Pdf/PdfService.cs index dccbc99c9..f7cf5f816 100644 --- a/src/Altinn.App.Core/Internal/Pdf/PdfService.cs +++ b/src/Altinn.App.Core/Internal/Pdf/PdfService.cs @@ -90,7 +90,8 @@ await _dataClient.InsertBinaryData( } /// - public async Task GeneratePdf(Instance instance, string taskId, CancellationToken ct) { + public async Task GeneratePdf(Instance instance, string taskId, CancellationToken ct) + { var language = GetOverriddenLanguage(); // Avoid a costly call if the language is allready overriden by the user language = language.IsNullOrEmpty() ? await GetLanguage() : language; @@ -98,7 +99,8 @@ public async Task GeneratePdf(Instance instance, string taskId, Cancella return await GeneratePdfContent(instance, taskId, ct, language); } - private async Task GeneratePdfContent(Instance instance, string taskId, CancellationToken ct, string language) { + private async Task GeneratePdfContent(Instance instance, string taskId, CancellationToken ct, string language) + { var baseUrl = _generalSettings.FormattedExternalAppBaseUrl(new AppIdentifier(instance)); var pagePath = _pdfGeneratorSettings.AppPdfPagePathTemplate.ToLowerInvariant().Replace("{instanceid}", instance.Id); @@ -154,7 +156,7 @@ private string GetOverriddenLanguage() if (_httpContextAccessor.HttpContext != null) { StringValues queryLanguage; - bool hasQueryLanguage = _httpContextAccessor.HttpContext.Request.Query.TryGetValue("language", out queryLanguage) || _httpContextAccessor.HttpContext.Request.Query.TryGetValue("lang", out queryLanguage); + bool hasQueryLanguage = _httpContextAccessor.HttpContext.Request.Query.TryGetValue("language", out queryLanguage) || _httpContextAccessor.HttpContext.Request.Query.TryGetValue("lang", out queryLanguage); if (hasQueryLanguage) { return queryLanguage.ToString(); diff --git a/src/Altinn.App.Core/Internal/Process/Action/IUserActionAuthorizerProvider.cs b/src/Altinn.App.Core/Internal/Process/Action/IUserActionAuthorizerProvider.cs index 49efd787e..861d6261e 100644 --- a/src/Altinn.App.Core/Internal/Process/Action/IUserActionAuthorizerProvider.cs +++ b/src/Altinn.App.Core/Internal/Process/Action/IUserActionAuthorizerProvider.cs @@ -11,12 +11,12 @@ public interface IUserActionAuthorizerProvider /// Gets or sets the action /// public string? Action { get; } - + /// /// Gets or sets the task id /// public string? TaskId { get; } - + /// /// Gets or sets the authorizer implementation /// diff --git a/src/Altinn.App.Core/Internal/Process/Action/UserActionAuthorizerProvider.cs b/src/Altinn.App.Core/Internal/Process/Action/UserActionAuthorizerProvider.cs index 39b55dbf2..c21a359b7 100644 --- a/src/Altinn.App.Core/Internal/Process/Action/UserActionAuthorizerProvider.cs +++ b/src/Altinn.App.Core/Internal/Process/Action/UserActionAuthorizerProvider.cs @@ -5,9 +5,9 @@ namespace Altinn.App.Core.Internal.Process.Action; /// /// Register a user action authorizer for a given action and/or task /// -public class UserActionAuthorizerProvider: IUserActionAuthorizerProvider +public class UserActionAuthorizerProvider : IUserActionAuthorizerProvider { - + /// /// Initializes a new instance of the class /// @@ -20,13 +20,13 @@ public UserActionAuthorizerProvider(string? taskId, string? action, IUserActionA Action = action; Authorizer = authorizer; } - + /// public string? Action { get; set; } - + /// public string? TaskId { get; set; } - + /// public IUserActionAuthorizer Authorizer { get; set; } } diff --git a/src/Altinn.App.Core/Internal/Process/Action/UserActionAuthorizerServiceCollectionExtension.cs b/src/Altinn.App.Core/Internal/Process/Action/UserActionAuthorizerServiceCollectionExtension.cs index dbb2a0bcf..08af22f80 100644 --- a/src/Altinn.App.Core/Internal/Process/Action/UserActionAuthorizerServiceCollectionExtension.cs +++ b/src/Altinn.App.Core/Internal/Process/Action/UserActionAuthorizerServiceCollectionExtension.cs @@ -21,7 +21,7 @@ public static IServiceCollection AddTransientUserActionAuthorizerForActionInTask { return services.RegisterUserActionAuthorizer(taskId, action); } - + /// /// Adds a transient user action authorizer to the service collection connected to a action in all tasks /// @@ -33,7 +33,7 @@ public static IServiceCollection AddTransientUserActionAuthorizerForActionInAllT { return services.RegisterUserActionAuthorizer(null, action); } - + /// /// Adds a transient user action authorizer to the service collection connected to all actions in a task /// @@ -45,7 +45,7 @@ public static IServiceCollection AddTransientUserActionAuthorizerForAllActionsIn { return services.RegisterUserActionAuthorizer(taskId, null); } - + /// /// Adds a transient user action authorizer to the service collection connected to all actions in all tasks /// @@ -56,7 +56,7 @@ public static IServiceCollection AddTransientUserActionAuthorizerForAllActionsIn { return services.RegisterUserActionAuthorizer(null, null); } - + private static IServiceCollection RegisterUserActionAuthorizer(this IServiceCollection services, string? taskId, string? action) where T : class, IUserActionAuthorizer { services.TryAddTransient(); diff --git a/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnAction.cs b/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnAction.cs index 9a10e1427..ac408d7b7 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnAction.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnAction.cs @@ -37,7 +37,7 @@ public AltinnAction(string id, ActionType actionType) Value = id; ActionType = actionType; } - + /// /// Gets or sets the ID of the action /// @@ -50,7 +50,7 @@ public AltinnAction(string id, ActionType actionType) [XmlAttribute("type", Namespace = "http://altinn.no/process")] public ActionType ActionType { get; set; } } - + /// /// Defines the different types of actions /// diff --git a/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnSignatureConfiguration.cs b/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnSignatureConfiguration.cs index c980c53fa..945a3eed9 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnSignatureConfiguration.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnSignatureConfiguration.cs @@ -13,13 +13,13 @@ public class AltinnSignatureConfiguration [XmlArray(ElementName = "dataTypesToSign", Namespace = "http://altinn.no/process", IsNullable = true)] [XmlArrayItem(ElementName = "dataType", Namespace = "http://altinn.no/process")] public List DataTypesToSign { get; set; } = new(); - + /// /// Set what dataTypeId that should be used for storing the signature /// [XmlElement("signatureDataType", Namespace = "http://altinn.no/process")] public string SignatureDataType { get; set; } - + /// /// Define what signature dataypes this signature should be unique from. Users that have sign any of the signatures in the list will not be able to sign this signature /// diff --git a/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnTaskExtension.cs b/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnTaskExtension.cs index 98ff963ee..ba4db6672 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnTaskExtension.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/AltinnExtensionProperties/AltinnTaskExtension.cs @@ -20,8 +20,8 @@ public class AltinnTaskExtension //[XmlElement(ElementName = "taskType", Namespace = "http://altinn.no/process/task", IsNullable = true)] [XmlElement("taskType", Namespace = "http://altinn.no/process")] public string? TaskType { get; set; } - - + + /// /// Gets or sets the configuration for signature /// diff --git a/src/Altinn.App.Core/Internal/Process/Elements/AppProcessElementInfo.cs b/src/Altinn.App.Core/Internal/Process/Elements/AppProcessElementInfo.cs index 02e528321..b8346db4f 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/AppProcessElementInfo.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/AppProcessElementInfo.cs @@ -6,7 +6,7 @@ namespace Altinn.App.Core.Internal.Process.Elements; /// /// Extended representation of a status object that holds the process state of an application instance. /// -public class AppProcessElementInfo: ProcessElementInfo +public class AppProcessElementInfo : ProcessElementInfo { /// /// Create a new instance of with no fields set. @@ -16,7 +16,7 @@ public AppProcessElementInfo() Actions = new Dictionary(); UserActions = new List(); } - + /// /// Create a new instance of with values copied from . /// @@ -37,24 +37,24 @@ public AppProcessElementInfo(ProcessElementInfo processElementInfo) /// /// Actions that can be performed and if the user is allowed to perform them. /// - [JsonPropertyName(name:"actions")] + [JsonPropertyName(name: "actions")] public Dictionary? Actions { get; set; } - + /// /// List of available actions for a task, both user and process tasks /// - [JsonPropertyName(name:"userActions")] + [JsonPropertyName(name: "userActions")] public List UserActions { get; set; } - + /// /// Indicates if the user has read access to the task. /// - [JsonPropertyName(name:"read")] + [JsonPropertyName(name: "read")] public bool HasReadAccess { get; set; } - + /// /// Indicates if the user has write access to the task. /// - [JsonPropertyName(name:"write")] + [JsonPropertyName(name: "write")] public bool HasWriteAccess { get; set; } } \ No newline at end of file diff --git a/src/Altinn.App.Core/Internal/Process/Elements/AppProcessState.cs b/src/Altinn.App.Core/Internal/Process/Elements/AppProcessState.cs index f57376d47..a118d15c4 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/AppProcessState.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/AppProcessState.cs @@ -6,7 +6,7 @@ namespace Altinn.App.Core.Internal.Process.Elements; /// Extended representation of a status object that holds the process state of an application instance. /// The process is defined by the application's process specification BPMN file. /// -public class AppProcessState: ProcessState +public class AppProcessState : ProcessState { /// /// Default constructor @@ -21,7 +21,7 @@ public AppProcessState() /// public AppProcessState(ProcessState? processState) { - if(processState == null) + if (processState == null) { return; } @@ -33,7 +33,7 @@ public AppProcessState(ProcessState? processState) } Ended = processState.Ended; EndEvent = processState.EndEvent; - + } /// /// Gets or sets a status object containing the task info of the currentTask of an ongoing process. diff --git a/src/Altinn.App.Core/Internal/Process/Elements/EndEvent.cs b/src/Altinn.App.Core/Internal/Process/Elements/EndEvent.cs index 7c92cffa8..caeac4a59 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/EndEvent.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/EndEvent.cs @@ -6,7 +6,7 @@ namespace Altinn.App.Core.Internal.Process.Elements /// /// Class representing the end event of a process /// - public class EndEvent: ProcessElement + public class EndEvent : ProcessElement { /// /// String representation of process element type diff --git a/src/Altinn.App.Core/Internal/Process/Elements/ExclusiveGateway.cs b/src/Altinn.App.Core/Internal/Process/Elements/ExclusiveGateway.cs index d108f28d4..a433bb92a 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/ExclusiveGateway.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/ExclusiveGateway.cs @@ -6,14 +6,14 @@ namespace Altinn.App.Core.Internal.Process.Elements /// /// Represents an exclusive gateway from a BPMN process definition. /// - public class ExclusiveGateway: ProcessElement + public class ExclusiveGateway : ProcessElement { /// /// Get or sets the default path of the exclusive gateway. /// [XmlAttribute("default")] public string? Default { get; set; } - + /// /// /// diff --git a/src/Altinn.App.Core/Internal/Process/Elements/ExtensionElements.cs b/src/Altinn.App.Core/Internal/Process/Elements/ExtensionElements.cs index d5db11e70..68ec9f5d4 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/ExtensionElements.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/ExtensionElements.cs @@ -13,7 +13,7 @@ public class ExtensionElements /// [XmlElement("taskExtension", Namespace = "http://altinn.no/process")] public AltinnTaskExtension? TaskExtension { get; set; } - + /// /// Gets or sets the altinn properties /// diff --git a/src/Altinn.App.Core/Internal/Process/Elements/NullTask.cs b/src/Altinn.App.Core/Internal/Process/Elements/NullTask.cs index b8e79271f..c3f4a2fbb 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/NullTask.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/NullTask.cs @@ -6,7 +6,7 @@ namespace Altinn.App.Core.Internal.Process.Elements; /// /// Null implementation. Used when no other can be found /// -public class NullTask: ITask +public class NullTask : ITask { /// public async Task HandleTaskStart(string elementId, Instance instance, Dictionary prefill) diff --git a/src/Altinn.App.Core/Internal/Process/Elements/ProcessTask.cs b/src/Altinn.App.Core/Internal/Process/Elements/ProcessTask.cs index b80957b8e..8bde96975 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/ProcessTask.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/ProcessTask.cs @@ -6,7 +6,7 @@ namespace Altinn.App.Core.Internal.Process.Elements /// /// Class representing the task of a process /// - public class ProcessTask: ProcessElement + public class ProcessTask : ProcessElement { /// /// Defines the extension elements diff --git a/src/Altinn.App.Core/Internal/Process/Elements/SequenceFlow.cs b/src/Altinn.App.Core/Internal/Process/Elements/SequenceFlow.cs index 809b44b41..30a764490 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/SequenceFlow.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/SequenceFlow.cs @@ -30,7 +30,7 @@ public class SequenceFlow /// [XmlAttribute("flowtype", Namespace = "http://altinn.no")] public string FlowType { get; set; } - + /// /// Gets or sets the condition expression of a sequence flow /// diff --git a/src/Altinn.App.Core/Internal/Process/Elements/StartEvent.cs b/src/Altinn.App.Core/Internal/Process/Elements/StartEvent.cs index bce1b600a..029bd8db5 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/StartEvent.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/StartEvent.cs @@ -6,7 +6,7 @@ namespace Altinn.App.Core.Internal.Process.Elements /// /// Class representing the start event of a process /// - public class StartEvent: ProcessElement + public class StartEvent : ProcessElement { /// /// String representation of process element type diff --git a/src/Altinn.App.Core/Internal/Process/Elements/TaskBase.cs b/src/Altinn.App.Core/Internal/Process/Elements/TaskBase.cs index 274a0a013..7eb8e9af6 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/TaskBase.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/TaskBase.cs @@ -6,7 +6,7 @@ namespace Altinn.App.Core.Internal.Process.Elements /// /// TaskBase with default implentation /// - public abstract class TaskBase: ITask + public abstract class TaskBase : ITask { /// /// hallooo asdf diff --git a/src/Altinn.App.Core/Internal/Process/Elements/UserAction.cs b/src/Altinn.App.Core/Internal/Process/Elements/UserAction.cs index 2556ec2f0..d289077e5 100644 --- a/src/Altinn.App.Core/Internal/Process/Elements/UserAction.cs +++ b/src/Altinn.App.Core/Internal/Process/Elements/UserAction.cs @@ -14,13 +14,13 @@ public class UserAction /// [JsonPropertyName("id")] public required string Id { get; set; } - + /// /// Gets or sets if the user is authorized to perform the action /// [JsonPropertyName("authorized")] public bool Authorized { get; set; } - + /// /// Gets or sets the type of action /// diff --git a/src/Altinn.App.Core/Internal/Process/IProcessReader.cs b/src/Altinn.App.Core/Internal/Process/IProcessReader.cs index 492688071..fe6b69649 100644 --- a/src/Altinn.App.Core/Internal/Process/IProcessReader.cs +++ b/src/Altinn.App.Core/Internal/Process/IProcessReader.cs @@ -13,7 +13,7 @@ public interface IProcessReader /// /// public List GetStartEvents(); - + /// /// Get ids of all defined StartEvents in the process /// @@ -26,13 +26,13 @@ public interface IProcessReader /// Id of process element /// true if elementId is of type StartEvent public bool IsStartEvent(string? elementId); - + /// /// Get all defined Tasks in the process /// /// public List GetProcessTasks(); - + /// /// Get ids of all defined Tasks in the process /// @@ -45,13 +45,13 @@ public interface IProcessReader /// Id of process element /// true if elementId is of type Task public bool IsProcessTask(string? elementId); - + /// /// Get all ExclusiveGateways defined in the process /// /// public List GetExclusiveGateways(); - + /// /// Get ids of all defined ExclusiveGateways in the process /// @@ -63,13 +63,13 @@ public interface IProcessReader /// /// public List GetEndEvents(); - + /// /// Get ids of all EndEvents defined in the process /// /// public List GetEndEventIds(); - + /// /// Check id element is EndEvent /// @@ -89,20 +89,20 @@ public interface IProcessReader /// Element to get the outgoing sequenceflows from /// Outgoing sequence flows public List GetOutgoingSequenceFlows(ProcessElement? flowElement); - + /// /// Get ids of all SequenceFlows defined in the process /// /// public List GetSequenceFlowIds(); - + /// /// Find all possible next elements from current element /// /// Current process element id /// public List GetNextElements(string? currentElementId); - + /// /// Returns StartEvent, Task or EndEvent with given Id, null if element not found /// diff --git a/src/Altinn.App.Core/Internal/Process/ITaskEvents.cs b/src/Altinn.App.Core/Internal/Process/ITaskEvents.cs index 87c8cbb6d..0026ae19d 100644 --- a/src/Altinn.App.Core/Internal/Process/ITaskEvents.cs +++ b/src/Altinn.App.Core/Internal/Process/ITaskEvents.cs @@ -15,7 +15,7 @@ public interface ITaskEvents /// Prefill data /// public Task OnStartProcessTask(string taskId, Instance instance, Dictionary prefill); - + /// /// Is called after the process task is ended. Method can update instance and data element metadata. /// @@ -23,12 +23,12 @@ public interface ITaskEvents /// Instance data /// public Task OnEndProcessTask(string endEvent, Instance instance); - + /// /// Is called after the process task is abonded. Method can update instance and data element metadata. /// /// task id of task to abandon /// Instance data public Task OnAbandonProcessTask(string taskId, Instance instance); - + } diff --git a/src/Altinn.App.Core/Internal/Process/ProcessEngine.cs b/src/Altinn.App.Core/Internal/Process/ProcessEngine.cs index 49e7b8d06..058379f3c 100644 --- a/src/Altinn.App.Core/Internal/Process/ProcessEngine.cs +++ b/src/Altinn.App.Core/Internal/Process/ProcessEngine.cs @@ -134,7 +134,7 @@ public async Task Next(ProcessNextRequest request) var actionHandler = _userActionService.GetActionHandler(request.Action); var actionResult = actionHandler is null ? UserActionResult.SuccessResult() : await actionHandler.HandleAction(new UserActionContext(request.Instance, userId.Value)); - + if (!actionResult.Success) { return new ProcessChangeResult() diff --git a/src/Altinn.App.Core/Internal/Process/ProcessEngineMetricsDecorator.cs b/src/Altinn.App.Core/Internal/Process/ProcessEngineMetricsDecorator.cs index 74a5000bd..f01150401 100644 --- a/src/Altinn.App.Core/Internal/Process/ProcessEngineMetricsDecorator.cs +++ b/src/Altinn.App.Core/Internal/Process/ProcessEngineMetricsDecorator.cs @@ -10,7 +10,7 @@ namespace Altinn.App.Core.Internal.Process; public class ProcessEngineMetricsDecorator : IProcessEngine { private readonly IProcessEngine _processEngine; - private static readonly Counter ProcessTaskStartCounter = Metrics.CreateCounter("altinn_app_process_start_count", "Number of tasks started", labelNames: "result" ); + private static readonly Counter ProcessTaskStartCounter = Metrics.CreateCounter("altinn_app_process_start_count", "Number of tasks started", labelNames: "result"); private static readonly Counter ProcessTaskNextCounter = Metrics.CreateCounter("altinn_app_process_task_next_count", "Number of tasks moved to next", "result", "action", "task"); private static readonly Counter ProcessTaskEndCounter = Metrics.CreateCounter("altinn_app_process_end_count", "Number of tasks ended", labelNames: "result"); private static readonly Counter ProcessTimeCounter = Metrics.CreateCounter("altinn_app_process_end_time_total", "Number of seconds used to complete instances", labelNames: "result"); @@ -36,8 +36,8 @@ public async Task StartProcess(ProcessStartRequest processS public async Task Next(ProcessNextRequest request) { var result = await _processEngine.Next(request); - ProcessTaskNextCounter.WithLabels(result.Success ? "success" : "failure", request.Action?? "", request.Instance.Process?.CurrentTask?.ElementId ?? "").Inc(); - if(result.ProcessStateChange?.NewProcessState?.Ended != null) + ProcessTaskNextCounter.WithLabels(result.Success ? "success" : "failure", request.Action ?? "", request.Instance.Process?.CurrentTask?.ElementId ?? "").Inc(); + if (result.ProcessStateChange?.NewProcessState?.Ended != null) { ProcessTaskEndCounter.WithLabels(result.Success ? "success" : "failure").Inc(); if (result.ProcessStateChange?.NewProcessState?.Started != null) diff --git a/src/Altinn.App.Core/Internal/Process/ProcessEventDispatcher.cs b/src/Altinn.App.Core/Internal/Process/ProcessEventDispatcher.cs index f87944693..63313ee9a 100644 --- a/src/Altinn.App.Core/Internal/Process/ProcessEventDispatcher.cs +++ b/src/Altinn.App.Core/Internal/Process/ProcessEventDispatcher.cs @@ -24,11 +24,11 @@ class ProcessEventDispatcher : IProcessEventDispatcher private readonly ILogger _logger; public ProcessEventDispatcher( - IInstanceClient instanceClient, + IInstanceClient instanceClient, IInstanceEventClient instanceEventClient, - ITaskEvents taskEvents, - IAppEvents appEvents, - IEventsClient eventsClient, + ITaskEvents taskEvents, + IAppEvents appEvents, + IEventsClient eventsClient, IOptions appSettings, ILogger logger) { @@ -78,8 +78,8 @@ public async Task RegisterEventWithEventsComponent(Instance instance) } } } - - + + private async Task DispatchProcessEventsToStorage(Instance instance, List? events) { string org = instance.Org; diff --git a/src/Altinn.App.Core/Internal/Process/ProcessNavigator.cs b/src/Altinn.App.Core/Internal/Process/ProcessNavigator.cs index 1bb44a063..aced56858 100644 --- a/src/Altinn.App.Core/Internal/Process/ProcessNavigator.cs +++ b/src/Altinn.App.Core/Internal/Process/ProcessNavigator.cs @@ -67,10 +67,11 @@ private async Task> NextFollowAndFilterGateways(Instance in var gateway = (ExclusiveGateway)directFlowTarget; List outgoingFlows = _processReader.GetOutgoingSequenceFlows(directFlowTarget); IProcessExclusiveGateway? gatewayFilter = null; - if(outgoingFlows.Any(a => a.ConditionExpression != null)) + if (outgoingFlows.Any(a => a.ConditionExpression != null)) { gatewayFilter = _gatewayFactory.GetProcessExclusiveGateway("AltinnExpressionsExclusiveGateway"); - } else + } + else { gatewayFilter = _gatewayFactory.GetProcessExclusiveGateway(directFlowTarget.Id); } @@ -86,7 +87,7 @@ private async Task> NextFollowAndFilterGateways(Instance in Action = action, DataTypeId = gateway.ExtensionElements?.GatewayExtension?.ConnectedDataTypeId }; - + filteredList = await gatewayFilter.FilterAsync(outgoingFlows, instance, gatewayInformation); } var defaultSequenceFlow = filteredList.Find(s => s.Id == gateway.Default); diff --git a/src/Altinn.App.Core/Internal/Process/ProcessReader.cs b/src/Altinn.App.Core/Internal/Process/ProcessReader.cs index 0d2b3d9fb..02d4884e0 100644 --- a/src/Altinn.App.Core/Internal/Process/ProcessReader.cs +++ b/src/Altinn.App.Core/Internal/Process/ProcessReader.cs @@ -127,7 +127,7 @@ public List GetSequenceFlowIds() return _definitions.Process.ExclusiveGateway.Find(e => e.Id == elementId); } - + /// public List GetNextElements(string? currentElementId) { @@ -157,7 +157,7 @@ public List GetOutgoingSequenceFlows(ProcessElement? flowElement) return GetSequenceFlows().FindAll(sf => flowElement.Outgoing.Contains(sf.Id)).ToList(); } - + /// public List GetAllFlowElements() { diff --git a/src/Altinn.App.Core/Internal/Sign/SignatureContext.cs b/src/Altinn.App.Core/Internal/Sign/SignatureContext.cs index d4635c138..952366642 100644 --- a/src/Altinn.App.Core/Internal/Sign/SignatureContext.cs +++ b/src/Altinn.App.Core/Internal/Sign/SignatureContext.cs @@ -21,7 +21,7 @@ public SignatureContext(InstanceIdentifier instanceIdentifier, string signatureD DataElementSignatures.AddRange(dataElementSignature); Signee = signee; } - + /// /// Create a new signing context for multiple data elements /// @@ -36,12 +36,12 @@ public SignatureContext(InstanceIdentifier instanceIdentifier, string signatureD DataElementSignatures = dataElementSignatures; Signee = signee; } - + /// /// The id of the DataType where the signature should be stored /// public string SignatureDataTypeId { get; } - + /// /// Identifier for the instance containing the data elements to sign /// @@ -50,8 +50,8 @@ public SignatureContext(InstanceIdentifier instanceIdentifier, string signatureD /// /// List of DataElements and whether they are signed or not /// - public List DataElementSignatures { get; } = new (); - + public List DataElementSignatures { get; } = new(); + /// /// The user performing the signing /// @@ -67,12 +67,12 @@ public class Signee /// User id of the user performing the signing /// public string UserId { get; set; } - + /// /// The SSN of the user performing the signing, set if the signer is a person /// public string? PersonNumber { get; set; } - + /// /// The organisation number of the user performing the signing, set if the signer is an organisation /// @@ -104,12 +104,12 @@ public DataElementSignature(string dataElementId, bool signed) DataElementId = dataElementId; Signed = signed; } - + /// /// ID of the DataElement that should be included in the signature /// public string DataElementId { get; } - + /// /// Whether the DataElement is signed or not /// diff --git a/src/Altinn.App.Core/Internal/Validation/FileValidationService.cs b/src/Altinn.App.Core/Internal/Validation/FileValidationService.cs index aae59bc1a..7a920b9ef 100644 --- a/src/Altinn.App.Core/Internal/Validation/FileValidationService.cs +++ b/src/Altinn.App.Core/Internal/Validation/FileValidationService.cs @@ -27,7 +27,7 @@ public FileValidationService(IFileValidatorFactory fileValidatorFactory) { List allErrors = new(); bool allSuccess = true; - + List fileValidators = _fileValidatorFactory.GetFileValidators(dataType.EnabledFileValidators).ToList(); foreach (IFileValidator fileValidator in fileValidators) { diff --git a/src/Altinn.App.Core/Models/AppIdentifier.cs b/src/Altinn.App.Core/Models/AppIdentifier.cs index daa345aea..3dd6dd358 100644 --- a/src/Altinn.App.Core/Models/AppIdentifier.cs +++ b/src/Altinn.App.Core/Models/AppIdentifier.cs @@ -62,7 +62,7 @@ public AppIdentifier(string id) /// /// Get an AppIdentifier from an Instance.AppID /// - public AppIdentifier(Instance instance) : this(instance.AppId) {} + public AppIdentifier(Instance instance) : this(instance.AppId) { } /// @@ -126,7 +126,7 @@ public static AppIdentifier CreateFromUrl(string url) Uri uri = new(url, UriKind.Absolute); // Remove the first slash as this will only result in an empty first segment when splitting. - string[] segments = uri.PathAndQuery[1..].Split("/"); + string[] segments = uri.PathAndQuery[1..].Split("/"); if (segments.Length < 2) { diff --git a/src/Altinn.App.Core/Models/CloudEvent.cs b/src/Altinn.App.Core/Models/CloudEvent.cs index c443b2681..5fa03e7ef 100644 --- a/src/Altinn.App.Core/Models/CloudEvent.cs +++ b/src/Altinn.App.Core/Models/CloudEvent.cs @@ -50,7 +50,7 @@ public class CloudEvent [JsonPropertyName("alternativesubject")] public string AlternativeSubject { get; set; } - /// + /// /// Gets or sets the cloudEvent data content. The event payload. /// The payload depends on the type and the dataschema. /// diff --git a/src/Altinn.App.Core/Models/DataList.cs b/src/Altinn.App.Core/Models/DataList.cs index 9bf1d6a8b..80bee9a49 100644 --- a/src/Altinn.App.Core/Models/DataList.cs +++ b/src/Altinn.App.Core/Models/DataList.cs @@ -18,6 +18,6 @@ public class DataList /// /// Gets or sets the metadata of the DataList. /// - public DataListMetadata _metaData { get; set; } = new DataListMetadata(); + public DataListMetadata _metaData { get; set; } = new DataListMetadata(); } } \ No newline at end of file diff --git a/src/Altinn.App.Core/Models/InstanceIdentifier.cs b/src/Altinn.App.Core/Models/InstanceIdentifier.cs index eb10aa707..229a7ea49 100644 --- a/src/Altinn.App.Core/Models/InstanceIdentifier.cs +++ b/src/Altinn.App.Core/Models/InstanceIdentifier.cs @@ -33,7 +33,7 @@ public InstanceIdentifier(string instanceId) /// Initializes a new instance of the class. /// /// Is the instance you want to get an idenifier from - public InstanceIdentifier(Instance instance) : this(instance.Id) {} + public InstanceIdentifier(Instance instance) : this(instance.Id) { } /// /// Initializes a new instance of the class. For instances without OwnerPartyId and InstanceId, ex: Stateless applications. @@ -88,7 +88,7 @@ public string GetInstanceId() { throw new ArgumentNullException(nameof(InstanceGuid), "No instance id available for instance"); } - + return $"{InstanceOwnerPartyId}/{InstanceGuid}"; } diff --git a/src/Altinn.App.Core/Models/MimeType.cs b/src/Altinn.App.Core/Models/MimeType.cs index 598170c7d..0a930aa16 100644 --- a/src/Altinn.App.Core/Models/MimeType.cs +++ b/src/Altinn.App.Core/Models/MimeType.cs @@ -64,7 +64,7 @@ private bool MimeTypeEquals(MimeType? other) return other != null && Type == other.Type && Aliases.SequenceEqual(other.Aliases); } - + /// /// Check if the mime type matches the given object /// Supported types are: diff --git a/src/Altinn.App.Core/Models/OnEntry.cs b/src/Altinn.App.Core/Models/OnEntry.cs index e22186ee5..64226be63 100644 --- a/src/Altinn.App.Core/Models/OnEntry.cs +++ b/src/Altinn.App.Core/Models/OnEntry.cs @@ -1,12 +1,14 @@ using Altinn.Platform.Storage.Interface.Models; using Newtonsoft.Json; -namespace Altinn.App.Core.Models { - +namespace Altinn.App.Core.Models +{ + /// /// The on entry configuration /// - public class OnEntry : OnEntryConfig { + public class OnEntry : OnEntryConfig + { /// /// Options for displaying the instance selection component diff --git a/src/Altinn.App.Core/Models/Process/ProcessChangeResult.cs b/src/Altinn.App.Core/Models/Process/ProcessChangeResult.cs index 4ae14a0a6..a4014bcda 100644 --- a/src/Altinn.App.Core/Models/Process/ProcessChangeResult.cs +++ b/src/Altinn.App.Core/Models/Process/ProcessChangeResult.cs @@ -17,7 +17,7 @@ public class ProcessChangeResult /// Gets or sets the error type if the process change was not successful /// public ProcessErrorType? ErrorType { get; set; } - + /// /// Gets or sets the process state change if the process change was successful /// @@ -33,12 +33,12 @@ public enum ProcessErrorType /// The process change was not allowed due to the current state of the process /// Conflict, - + /// /// The process change lead to an internal error /// Internal, - + /// /// The user is not authorized to perform the process change /// diff --git a/src/Altinn.App.Core/Models/Result/ServiceResult.cs b/src/Altinn.App.Core/Models/Result/ServiceResult.cs index 7219662a9..0c7034f9a 100644 --- a/src/Altinn.App.Core/Models/Result/ServiceResult.cs +++ b/src/Altinn.App.Core/Models/Result/ServiceResult.cs @@ -17,7 +17,7 @@ public class ServiceResult /// The error returned when the result is an error /// public TU? Error { get; } - + /// /// Whether the result is Ok or an Error /// @@ -37,7 +37,7 @@ private ServiceResult(T? ok, TU? error, bool success) /// /// public static implicit operator ServiceResult(T okData) => new(okData, default, true); - + /// /// Implicitly create a ServiceResult with an error result /// diff --git a/src/Altinn.App.Core/Models/UserAction/ActionError.cs b/src/Altinn.App.Core/Models/UserAction/ActionError.cs index 1b249832e..97dc59f51 100644 --- a/src/Altinn.App.Core/Models/UserAction/ActionError.cs +++ b/src/Altinn.App.Core/Models/UserAction/ActionError.cs @@ -18,7 +18,7 @@ public class ActionError /// [JsonPropertyName("message")] public string Message { get; set; } = string.Empty; - + /// /// Error metadata /// diff --git a/src/Altinn.App.Core/Models/UserAction/UserActionContext.cs b/src/Altinn.App.Core/Models/UserAction/UserActionContext.cs index a76293229..ff636c2f8 100644 --- a/src/Altinn.App.Core/Models/UserAction/UserActionContext.cs +++ b/src/Altinn.App.Core/Models/UserAction/UserActionContext.cs @@ -26,17 +26,17 @@ public UserActionContext(Instance instance, int userId, string? buttonId = null, /// The instance the action is performed on /// public Instance Instance { get; } - + /// /// The user performing the action /// public int UserId { get; } - + /// /// The id of the button that triggered the action (optional) /// public string? ButtonId { get; } - + /// /// Additional metadata for the action /// diff --git a/src/Altinn.App.Core/Models/UserAction/UserActionResult.cs b/src/Altinn.App.Core/Models/UserAction/UserActionResult.cs index 3bf974d04..fe4e9df78 100644 --- a/src/Altinn.App.Core/Models/UserAction/UserActionResult.cs +++ b/src/Altinn.App.Core/Models/UserAction/UserActionResult.cs @@ -20,12 +20,12 @@ public class UserActionResult /// Actions for the client to perform after the user action has been handled /// public List? ClientActions { get; set; } - + /// /// Validation issues that should be displayed to the user /// public ActionError? Error { get; set; } - + /// /// Creates a success result /// @@ -40,7 +40,7 @@ public static UserActionResult SuccessResult(List? clientActions = }; return userActionResult; } - + /// /// Creates a failure result /// diff --git a/test/Altinn.App.Api.Tests/Controllers/DataControllerTests.cs b/test/Altinn.App.Api.Tests/Controllers/DataControllerTests.cs index 7ecf2f530..a1526cfaa 100644 --- a/test/Altinn.App.Api.Tests/Controllers/DataControllerTests.cs +++ b/test/Altinn.App.Api.Tests/Controllers/DataControllerTests.cs @@ -79,7 +79,7 @@ public async Task CreateDataElement_BinaryPdf_AnalyserShouldRunOk() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - + [Fact] public async Task CreateDataElement_ZeroBytes_BinaryPdf_AnalyserShouldReturnBadRequest() { @@ -93,7 +93,7 @@ public async Task CreateDataElement_ZeroBytes_BinaryPdf_AnalyserShouldReturnBadR string org = "tdd"; string app = "contributer-restriction"; HttpClient client = GetRootedClient(org, app); - + Guid guid = new Guid("0fc98a23-fe31-4ef5-8fb9-dd3f479354cd"); TestData.DeleteInstance(org, app, 1337, guid); TestData.PrepareInstance(org, app, 1337, guid); @@ -115,7 +115,8 @@ public async Task CreateDataElement_ZeroBytes_BinaryPdf_AnalyserShouldReturnBadR TestData.DeleteInstanceAndData(org, app, 1337, guid); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - Assert.Equal("Invalid data provided. Error: The file is zero bytes.",response.Content.ReadAsStringAsync().Result); + var responseContent = await response.Content.ReadAsStringAsync(); + Assert.Equal("Invalid data provided. Error: The file is zero bytes.", responseContent); } [Fact] diff --git a/test/Altinn.App.Api.Tests/Controllers/DataController_PutTests.cs b/test/Altinn.App.Api.Tests/Controllers/DataController_PutTests.cs index 629cf5cd6..97e3a33b2 100644 --- a/test/Altinn.App.Api.Tests/Controllers/DataController_PutTests.cs +++ b/test/Altinn.App.Api.Tests/Controllers/DataController_PutTests.cs @@ -18,7 +18,7 @@ public class DataController_PutTests : ApiTestBase, IClassFixture _dataProcessor = new(); - private static readonly JsonSerializerOptions JsonSerializerOptions = new () + private static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; @@ -60,7 +60,7 @@ public async Task PutDataElement_TestSinglePartUpdate_ReturnsOk() var createDataElementResponseParsed = JsonSerializer.Deserialize(createDataElementResponseContent, JsonSerializerOptions)!; var dataGuid = createDataElementResponseParsed.Id; - + // Update data element using var updateDataElementContent = new StringContent("""{"melding":{"name": "Ola Olsen"}}""", System.Text.Encoding.UTF8, "application/json"); @@ -94,7 +94,7 @@ public async Task PutDataElement_TestMultiPartUpdateWithCustomDataProcessor_Retu return Task.CompletedTask; }); - + // Run previous test with different setup // Setup test data string org = "tdd"; @@ -123,7 +123,7 @@ await client.PostAsync($"/{org}/{app}/instances/{instanceId}/data?dataType=defau var createDataElementResponseParsed = JsonSerializer.Deserialize(createDataElementResponseContent, JsonSerializerOptions)!; var dataGuid = createDataElementResponseParsed.Id; - + // Verify stored data var firstReadDataElementResponse = await client.GetAsync($"/{org}/{app}/instances/{instanceId}/data/{dataGuid}"); var firstReadDataElementResponseContent = await firstReadDataElementResponse.Content.ReadAsStringAsync(); @@ -147,10 +147,10 @@ await client.PostAsync($"/{org}/{app}/instances/{instanceId}/data?dataType=defau readDataElementResponseParsed.Melding!.Name.Should().Be("Ola Olsen"); readDataElementResponseParsed.Melding.Toggle.Should().BeTrue(); - _dataProcessor.Verify(p=>p.ProcessDataRead(It.IsAny(), It.Is(dataId => dataId == Guid.Parse(dataGuid)), It.IsAny(), null), Times.Exactly(2)); + _dataProcessor.Verify(p => p.ProcessDataRead(It.IsAny(), It.Is(dataId => dataId == Guid.Parse(dataGuid)), It.IsAny(), null), Times.Exactly(2)); _dataProcessor.Verify(p => p.ProcessDataWrite(It.IsAny(), It.Is(dataId => dataId == Guid.Parse(dataGuid)), It.IsAny(), It.IsAny(), null), Times.Exactly(1)); // TODO: Shouldn't this be 2 because of the first write? _dataProcessor.VerifyNoOtherCalls(); - + } diff --git a/test/Altinn.App.Api.Tests/Controllers/EventsReceiverControllerTests.cs b/test/Altinn.App.Api.Tests/Controllers/EventsReceiverControllerTests.cs index 06e17b730..03de46a90 100644 --- a/test/Altinn.App.Api.Tests/Controllers/EventsReceiverControllerTests.cs +++ b/test/Altinn.App.Api.Tests/Controllers/EventsReceiverControllerTests.cs @@ -75,9 +75,9 @@ public async Task Post_NonValidEventType_ShouldReturnBadRequest() { Content = new StringContent(System.Text.Json.JsonSerializer.Serialize(cloudEvent), Encoding.UTF8, "application/json") }; - + HttpResponseMessage response = await client.SendAsync(request); - + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); } } diff --git a/test/Altinn.App.Api.Tests/Controllers/InstancesController_CopyInstanceTests.cs b/test/Altinn.App.Api.Tests/Controllers/InstancesController_CopyInstanceTests.cs index 7e7f05056..9d97db270 100644 --- a/test/Altinn.App.Api.Tests/Controllers/InstancesController_CopyInstanceTests.cs +++ b/test/Altinn.App.Api.Tests/Controllers/InstancesController_CopyInstanceTests.cs @@ -56,8 +56,8 @@ public InstancesController_CopyInstanceTests() ControllerContext controllerContext = new ControllerContext() { HttpContext = _httpContextMock.Object - }; - + }; + SUT = new InstancesController( _logger.Object, _registrer.Object, @@ -74,7 +74,7 @@ public InstancesController_CopyInstanceTests() _profile.Object, _processEngine.Object, _oarganizationClientMock.Object) - { + { ControllerContext = controllerContext }; } @@ -218,7 +218,7 @@ public async Task CopyInstance_InstanceDoesNotExists_ReturnsBadRequest() Guid instanceGuid = Guid.NewGuid(); // Storage returns Forbidden if the given instance id is wrong. - PlatformHttpException platformHttpException = + PlatformHttpException platformHttpException = await PlatformHttpException.CreateAsync(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)); _httpContextMock.Setup(httpContext => httpContext.User).Returns(PrincipalUtil.GetUserPrincipal(1337, null)); @@ -361,11 +361,11 @@ public async Task CopyInstance_EverythingIsFine_ReturnsRedirect() _instanceClient.Setup(i => i.GetInstance(It.IsAny())).ReturnsAsync(instance); _instantiationValidator.Setup(v => v.Validate(It.IsAny())).ReturnsAsync(instantiationValidationResult); _processEngine.Setup(p => p.StartProcess(It.IsAny())) - .ReturnsAsync(() => { return new ProcessChangeResult(){Success = true}; }); + .ReturnsAsync(() => { return new ProcessChangeResult() { Success = true }; }); _processEngine.Setup(p => p.UpdateInstanceAndRerunEvents(It.IsAny(), It.IsAny>())); - _data.Setup(p=>p.GetFormData(instanceGuid, It.IsAny()!, Org, AppName, InstanceOwnerPartyId, dataGuid)) + _data.Setup(p => p.GetFormData(instanceGuid, It.IsAny()!, Org, AppName, InstanceOwnerPartyId, dataGuid)) .ReturnsAsync(new { test = "test" }); - _data.Setup(p=>p.InsertFormData(It.IsAny(), instanceGuid, It.IsAny()!, Org, AppName, InstanceOwnerPartyId, dataTypeId)) + _data.Setup(p => p.InsertFormData(It.IsAny(), instanceGuid, It.IsAny()!, Org, AppName, InstanceOwnerPartyId, dataTypeId)) .ReturnsAsync(new DataElement()); // Act @@ -390,17 +390,17 @@ private static ApplicationMetadata CreateApplicationMetadata(string org, string return new($"{org}/{app}") { CopyInstanceSettings = new CopyInstanceSettings { Enabled = enableCopyInstance }, - DataTypes = new List - { - new DataType - { + DataTypes = new List + { + new DataType + { Id = "data_type_1", AppLogic = new ApplicationLogic { ClassRef = "App.Models.Skjema", }, TaskId = "First" - } + } }, Org = org }; diff --git a/test/Altinn.App.Api.Tests/Controllers/PdfControllerTests.cs b/test/Altinn.App.Api.Tests/Controllers/PdfControllerTests.cs index 2d1654541..a384819f4 100644 --- a/test/Altinn.App.Api.Tests/Controllers/PdfControllerTests.cs +++ b/test/Altinn.App.Api.Tests/Controllers/PdfControllerTests.cs @@ -46,15 +46,15 @@ public PdfControllerTests() _instanceClient .Setup(a => a.GetInstance(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .Returns(Task.FromResult(new Instance() + { + Org = org, + AppId = $"{org}/{app}", + Id = $"{partyId}/{instanceId}", + Process = new ProcessState() { - Org = org, - AppId = $"{org}/{app}", - Id = $"{partyId}/{instanceId}", - Process = new ProcessState() - { - CurrentTask = new ProcessElementInfo() { ElementId = taskId, }, - } - })); + CurrentTask = new ProcessElementInfo() { ElementId = taskId, }, + } + })); } [Fact] @@ -77,7 +77,7 @@ public async Task Request_In_Prod_Should_Be_Blocked() var pdfController = new PdfController(_instanceClient.Object, _pdfFormatter.Object, _appResources.Object, _appModel.Object, _dataClient.Object, env.Object, pdfService); var result = await pdfController.GetPdfPreview(org, app, partyId, instanceId); - + result.Should().BeOfType(typeof(NotFoundResult)); handler.Protected().Verify("SendAsync", Times.Never(), ItExpr.IsAny(), ItExpr.IsAny()); } @@ -113,7 +113,7 @@ public async Task Request_In_Dev_Should_Generate() var result = await pdfController.GetPdfPreview(org, app, partyId, instanceId); result.Should().BeOfType(typeof(FileStreamResult)); } - + requestBody.Should().Contain(@"url"":""http://local.altinn.cloud/org/app/#/instance/12345/e11e3e0b-a45c-48fb-a968-8d4ddf868c80?pdf=1"); requestBody.Should().NotContain(@"name"":""frontendVersion"); } diff --git a/test/Altinn.App.Api.Tests/Controllers/StatelessDataControllerTests.cs b/test/Altinn.App.Api.Tests/Controllers/StatelessDataControllerTests.cs index 9c7adce79..080607738 100644 --- a/test/Altinn.App.Api.Tests/Controllers/StatelessDataControllerTests.cs +++ b/test/Altinn.App.Api.Tests/Controllers/StatelessDataControllerTests.cs @@ -107,11 +107,11 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) options.ClearProviders(); }); - builder.ConfigureServices(services=> + builder.ConfigureServices(services => { - services.AddTransient((sp)=>ProfileClientMoq.Object); - services.AddTransient((sp)=>RegisterClientMoq.Object); - services.AddTransient((sp)=>AppResourcesMoq.Object); + services.AddTransient((sp) => ProfileClientMoq.Object); + services.AddTransient((sp) => RegisterClientMoq.Object); + services.AddTransient((sp) => AppResourcesMoq.Object); }); } } @@ -121,15 +121,15 @@ public async void Get_Returns_BadRequest_when_party_header_count_greater_than_on { // Arrange var factory = new StatelessDataControllerWebApplicationFactory(); - + var client = factory.CreateClient(); string token = PrincipalUtil.GetToken(1337, null); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); using var request = new HttpRequestMessage(HttpMethod.Get, "/tdd/demo-app/v1/data?dataType=xml"); - request.Headers.Add("party", new string[]{"partyid:234", "partyid:234"}); // Double header + request.Headers.Add("party", new string[] { "partyid:234", "partyid:234" }); // Double header - factory.AppResourcesMoq.Setup(ar=>ar.GetClassRefForLogicDataType(It.IsAny())).Returns("Not.In.Valid.Namespace.ClassRef"); - factory.RegisterClientMoq.Setup(p=>p.GetParty(234)).ReturnsAsync(new Platform.Register.Models.Party + factory.AppResourcesMoq.Setup(ar => ar.GetClassRefForLogicDataType(It.IsAny())).Returns("Not.In.Valid.Namespace.ClassRef"); + factory.RegisterClientMoq.Setup(p => p.GetParty(234)).ReturnsAsync(new Platform.Register.Models.Party { PartyId = 234, }); @@ -142,21 +142,21 @@ public async void Get_Returns_BadRequest_when_party_header_count_greater_than_on response.StatusCode.Should().Be(System.Net.HttpStatusCode.BadRequest); responseText.Should().Contain("Invalid party header."); } - + [Fact] public async void Get_Returns_Forbidden_when_party_has_no_rights() { // Arrange var factory = new StatelessDataControllerWebApplicationFactory(); - + var client = factory.CreateClient(); string token = PrincipalUtil.GetToken(1337, null); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); using var request = new HttpRequestMessage(HttpMethod.Get, "/tdd/demo-app/v1/data?dataType=xml"); - request.Headers.Add("party", new string[]{"partyid:234"}); + request.Headers.Add("party", new string[] { "partyid:234" }); - factory.AppResourcesMoq.Setup(ar=>ar.GetClassRefForLogicDataType(It.IsAny())).Returns("Not.In.Valid.Namespace.ClassRef"); - factory.RegisterClientMoq.Setup(p=>p.GetParty(234)).ReturnsAsync(new Platform.Register.Models.Party + factory.AppResourcesMoq.Setup(ar => ar.GetClassRefForLogicDataType(It.IsAny())).Returns("Not.In.Valid.Namespace.ClassRef"); + factory.RegisterClientMoq.Setup(p => p.GetParty(234)).ReturnsAsync(new Platform.Register.Models.Party { PartyId = 234, }); @@ -239,7 +239,7 @@ public async void Get_Returns_BadRequest_when_instance_owner_is_empty_user_in_co registerMock.VerifyNoOtherCalls(); pdpMock.VerifyNoOtherCalls(); } - + [Fact] public async void Get_Returns_Forbidden_when_returned_descision_is_Deny() { @@ -276,7 +276,7 @@ public async void Get_Returns_Forbidden_when_returned_descision_is_Deny() } } }); - registerMock.Setup(r=>r.GetParty(12345)).ReturnsAsync(new Platform.Register.Models.Party + registerMock.Setup(r => r.GetParty(12345)).ReturnsAsync(new Platform.Register.Models.Party { PartyId = 12345, }); @@ -289,14 +289,14 @@ public async void Get_Returns_Forbidden_when_returned_descision_is_Deny() result.Should().BeOfType().Which.StatusCode.Should().Be(403); appResourcesMock.Verify(x => x.GetClassRefForLogicDataType(dataType), Times.Once); appResourcesMock.VerifyNoOtherCalls(); - registerMock.Verify(r=>r.GetParty(12345)); + registerMock.Verify(r => r.GetParty(12345)); pdpMock.Verify(p => p.GetDecisionForRequest(It.IsAny())); pdpMock.VerifyNoOtherCalls(); dataProcessorMock.VerifyNoOtherCalls(); prefillMock.VerifyNoOtherCalls(); registerMock.VerifyNoOtherCalls(); } - + [Fact] public async void Get_Returns_OK_with_appModel() { @@ -336,7 +336,7 @@ public async void Get_Returns_OK_with_appModel() }); appModelMock.Setup(a => a.Create(classRef)) .Returns(new DummyModel()); - registerMock.Setup(r=>r.GetParty(12345)).ReturnsAsync(new Platform.Register.Models.Party + registerMock.Setup(r => r.GetParty(12345)).ReturnsAsync(new Platform.Register.Models.Party { PartyId = 12345, }); @@ -353,7 +353,7 @@ public async void Get_Returns_OK_with_appModel() appModelMock.Verify(a => a.Create(classRef), Times.Once); prefillMock.Verify(p => p.PrefillDataModel("12345", dataType, It.IsAny(), null)); dataProcessorMock.Verify(a => a.ProcessDataRead(It.IsAny(), null, It.IsAny(), null)); - registerMock.Verify(r=>r.GetParty(12345)); + registerMock.Verify(r => r.GetParty(12345)); appResourcesMock.VerifyNoOtherCalls(); pdpMock.VerifyNoOtherCalls(); dataProcessorMock.VerifyNoOtherCalls(); diff --git a/test/Altinn.App.Api.Tests/Controllers/StatelessPagesControllerTests.cs b/test/Altinn.App.Api.Tests/Controllers/StatelessPagesControllerTests.cs index b62d67387..3fcf04b3b 100644 --- a/test/Altinn.App.Api.Tests/Controllers/StatelessPagesControllerTests.cs +++ b/test/Altinn.App.Api.Tests/Controllers/StatelessPagesControllerTests.cs @@ -80,17 +80,17 @@ public async Task GetPageOrder_Returns_BadRequest_when_datatype_null() appResourcesMock.Object, pageOrderMock.Object ); - + // Act var response = await controller.GetPageOrder(org, app, layoutSetId, currentpage, null, formdata); - + // Assert response.Result.Should().BeOfType(); appResourcesMock.VerifyNoOtherCalls(); pageOrderMock.VerifyNoOtherCalls(); appModelMock.VerifyNoOtherCalls(); } - + [Fact] public async Task GetPageOrder_Returns_BadRequest_when_datatype_empty() { @@ -103,10 +103,10 @@ public async Task GetPageOrder_Returns_BadRequest_when_datatype_empty() appResourcesMock.Object, pageOrderMock.Object ); - + // Act var response = await controller.GetPageOrder(org, app, layoutSetId, currentpage, string.Empty, formdata); - + // Assert response.Result.Should().BeOfType(); appResourcesMock.VerifyNoOtherCalls(); diff --git a/test/Altinn.App.Api.Tests/Controllers/TestResources/DummyModel.cs b/test/Altinn.App.Api.Tests/Controllers/TestResources/DummyModel.cs index ade169446..d9162e08a 100644 --- a/test/Altinn.App.Api.Tests/Controllers/TestResources/DummyModel.cs +++ b/test/Altinn.App.Api.Tests/Controllers/TestResources/DummyModel.cs @@ -1,7 +1,7 @@ namespace Altinn.App.Api.Tests.Controllers.TestResources; public class DummyModel -{ +{ public string Name { get; set; } public int Age { get; set; } @@ -23,4 +23,9 @@ public override bool Equals(object? obj) return this.Name == dummy.Name && this.Age == dummy.Age; } + + public override int GetHashCode() + { + throw new NotImplementedException(); + } } \ No newline at end of file diff --git a/test/Altinn.App.Api.Tests/Controllers/TextsControllerTests.cs b/test/Altinn.App.Api.Tests/Controllers/TextsControllerTests.cs index 01d5482d7..16b9128bf 100644 --- a/test/Altinn.App.Api.Tests/Controllers/TextsControllerTests.cs +++ b/test/Altinn.App.Api.Tests/Controllers/TextsControllerTests.cs @@ -32,15 +32,15 @@ public async Task Get_RetrunsTexts_when_found() } } }; - + var appResourceMock = new Mock(); appResourceMock.Setup(a => a.GetTexts(org, app, language)) .Returns(Task.FromResult(expected)); - + // Act var controller = new TextsController(appResourceMock.Object); var result = await controller.Get(org, app, language); - + // Assert var resultValue = result.Value; resultValue.Should().NotBeNull(); @@ -48,7 +48,7 @@ public async Task Get_RetrunsTexts_when_found() appResourceMock.Verify(a => a.GetTexts(org, app, language), Times.Once); appResourceMock.VerifyNoOtherCalls(); } - + [Fact] public async Task Get_checks_for_nb_text_if_language_specific_not_found_and_return_404_if_not_found() { @@ -71,7 +71,7 @@ public async Task Get_checks_for_nb_text_if_language_specific_not_found_and_retu } } }; - + var appResourceMock = new Mock(); appResourceMock.Setup(a => a.GetTexts(org, app, language)) .Returns(Task.FromResult(null)); @@ -80,7 +80,7 @@ public async Task Get_checks_for_nb_text_if_language_specific_not_found_and_retu // Act var controller = new TextsController(appResourceMock.Object); var result = await controller.Get(org, app, language); - + // Assert var resultValue = result.Value; result.Result.Should().BeOfType(); @@ -89,20 +89,20 @@ public async Task Get_checks_for_nb_text_if_language_specific_not_found_and_retu appResourceMock.Verify(a => a.GetTexts(org, app, "nb"), Times.Once); appResourceMock.VerifyNoOtherCalls(); } - + [Fact] public async Task Get_returns_bad_request_when_language_has_length_greater_than_two() { // Arrange const string org = "ttd"; const string app = "unit-app"; - + var appResourceMock = new Mock(); - + // Act var controller = new TextsController(appResourceMock.Object); var result = await controller.Get(org, app, "null"); - + // Assert result.Result.Should().BeOfType(); var resultValue = result.Value; diff --git a/test/Altinn.App.Api.Tests/Controllers/ValidateController_ValidateInstanceTests.cs b/test/Altinn.App.Api.Tests/Controllers/ValidateController_ValidateInstanceTests.cs index dfeda42eb..edc98a818 100644 --- a/test/Altinn.App.Api.Tests/Controllers/ValidateController_ValidateInstanceTests.cs +++ b/test/Altinn.App.Api.Tests/Controllers/ValidateController_ValidateInstanceTests.cs @@ -31,7 +31,7 @@ public class ValidateControllerValidateInstanceTests : ApiTestBase, IClassFixtur private readonly Mock _dataProcessorMock = new(MockBehavior.Strict); private readonly Mock _formDataValidatorMock = new(MockBehavior.Strict); - private static readonly JsonSerializerOptions JsonSerializerOptions = new () + private static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true, @@ -112,7 +112,7 @@ public async Task ValidateInstance_WithLegacyFormDataValidator() .Returns( (object data, ModelStateDictionary issues) => { - issues.AddModelError((Skjema s)=>s.Melding!.NestedList, "*FIXED*CustomErrorText"); + issues.AddModelError((Skjema s) => s.Melding!.NestedList, "*FIXED*CustomErrorText"); return Task.CompletedTask; }).Verifiable(Times.Once); @@ -126,12 +126,12 @@ public async Task ValidateInstance_WithLegacyFormDataValidator() response.Should().HaveStatusCode(HttpStatusCode.OK); var parsedResponse = ParseResponse>(responseString); parsedResponse.Should().HaveCount(2); - var taskIssue = parsedResponse.Should().ContainSingle(i=>i.DataElementId == null).Which; + var taskIssue = parsedResponse.Should().ContainSingle(i => i.DataElementId == null).Which; taskIssue.Field.Should().BeNull(); taskIssue.Description.Should().Be("TaskErrorText"); taskIssue.Severity.Should().Be(ValidationIssueSeverity.Error); - var dataIssue = parsedResponse.Should().ContainSingle(i=>i.DataElementId != null).Which; + var dataIssue = parsedResponse.Should().ContainSingle(i => i.DataElementId != null).Which; dataIssue.Field.Should().Be("melding.nested_list"); dataIssue.Description.Should().Be("CustomErrorText"); dataIssue.Severity.Should().Be(ValidationIssueSeverity.Fixed); diff --git a/test/Altinn.App.Api.Tests/Data/TestData.cs b/test/Altinn.App.Api.Tests/Data/TestData.cs index e3aa8e104..a19d1f7c7 100644 --- a/test/Altinn.App.Api.Tests/Data/TestData.cs +++ b/test/Altinn.App.Api.Tests/Data/TestData.cs @@ -20,8 +20,8 @@ public static string GetApplicationDirectory(string org, string app) return Path.Combine(testDataDirectory, "apps", org, app); } - public static string GetAppSpecificTestdataDirectory(string org, string app) - { + public static string GetAppSpecificTestdataDirectory(string org, string app) + { var appDirectory = GetApplicationDirectory(org, app); return Path.Join(appDirectory, "_testdata_"); } @@ -89,7 +89,7 @@ public static string GetDataBlobPath(string org, string app, int instanceOwnerId public static string GetTestDataRolesFolder(int userId, int resourcePartyId) { string testDataDirectory = GetTestDataRootDirectory(); - return Path.Combine(testDataDirectory, "authorization","roles", "User_" + userId, "party_" + resourcePartyId, "roles.json"); + return Path.Combine(testDataDirectory, "authorization", "roles", "User_" + userId, "party_" + resourcePartyId, "roles.json"); } public static string GetAltinnAppsPolicyPath(string org, string app) @@ -103,7 +103,7 @@ public static string GetAltinnProfilePath() string testDataDirectory = GetTestDataRootDirectory(); return Path.Combine(testDataDirectory, "Register", "Party"); } - + public static string GetRegisterProfilePath() { string testDataDirectory = GetTestDataRootDirectory(); @@ -134,7 +134,7 @@ public static void PrepareInstance(string org, string app, int instanceOwnerId, File.Copy(preInstancePath, instancePath, true); string dataPath = GetDataDirectory(org, app, instanceOwnerId, instanceGuid); - + if (Directory.Exists(dataPath)) { foreach (string filePath in Directory.GetFiles(dataPath, "*.*", SearchOption.AllDirectories)) diff --git a/test/Altinn.App.Api.Tests/Data/apps/tdd/eformidling-app/logic/App.cs b/test/Altinn.App.Api.Tests/Data/apps/tdd/eformidling-app/logic/App.cs index 3a639c958..ccb4a224e 100644 --- a/test/Altinn.App.Api.Tests/Data/apps/tdd/eformidling-app/logic/App.cs +++ b/test/Altinn.App.Api.Tests/Data/apps/tdd/eformidling-app/logic/App.cs @@ -31,7 +31,7 @@ public object Create(string classRef) throw new ArgumentException($"Could not find type {classRef}"); } - object? appInstance = Activator.CreateInstance(appType); + object? appInstance = Activator.CreateInstance(appType); return appInstance ?? throw new ArgumentException($"Could not create instance of {classRef}"); } diff --git a/test/Altinn.App.Api.Tests/Helpers/RequestHandling/DataRestrictionValidationTests.cs b/test/Altinn.App.Api.Tests/Helpers/RequestHandling/DataRestrictionValidationTests.cs index 730bba515..4acac2fd7 100644 --- a/test/Altinn.App.Api.Tests/Helpers/RequestHandling/DataRestrictionValidationTests.cs +++ b/test/Altinn.App.Api.Tests/Helpers/RequestHandling/DataRestrictionValidationTests.cs @@ -36,7 +36,7 @@ public void CompliesWithDataRestrictions_returns_false_with_413_status_if_conten (bool valid, List errors) = DataRestrictionValidation.CompliesWithDataRestrictions(httpContext.Request, dataType); valid.Should().BeFalse(); errors.Should().NotBeNull(); - errors.Should().BeOfType(typeof(List)); + errors.Should().BeOfType(typeof(List)); errors.FirstOrDefault()!.Description.Should().BeEquivalentTo("Invalid data provided. Error: Binary attachment exceeds limit of 1048576"); } diff --git a/test/Altinn.App.Api.Tests/Helpers/StartupHelperTests.cs b/test/Altinn.App.Api.Tests/Helpers/StartupHelperTests.cs index 1e32e654d..50854b086 100644 --- a/test/Altinn.App.Api.Tests/Helpers/StartupHelperTests.cs +++ b/test/Altinn.App.Api.Tests/Helpers/StartupHelperTests.cs @@ -25,7 +25,7 @@ public void IncludeXmlComments_calls_delegate_function_with_expected_values() testDouble.GetStrings().Should().Equal($"{AppContext.BaseDirectory}Altinn.App.Api.Tests.xml", $"{AppContext.BaseDirectory}Altinn.App.Api.xml"); testDouble.GetBools().Should().Equal(false, false); } - + [Fact] public void IncludeXmlComments_discards_exceptions() { diff --git a/test/Altinn.App.Api.Tests/Mappers/SimpleInstanceMapperTests.cs b/test/Altinn.App.Api.Tests/Mappers/SimpleInstanceMapperTests.cs index 5a48ced63..c4ab8ce52 100644 --- a/test/Altinn.App.Api.Tests/Mappers/SimpleInstanceMapperTests.cs +++ b/test/Altinn.App.Api.Tests/Mappers/SimpleInstanceMapperTests.cs @@ -29,16 +29,16 @@ public void MapInstanceListToSimpleInstanceList_Substitutes_LastChangedBy_FromUs new SimpleInstance { Id = "1", LastChanged = DateTime.Today, LastChangedBy = "User1" }, new SimpleInstance { Id = "2", LastChanged = DateTime.Today, LastChangedBy = "User2" } }; - + // Act var simpleInstances = SimpleInstanceMapper.MapInstanceListToSimpleInstanceList(instances, userDictionary); - + // Assert Assert.Equal(expected.Count, simpleInstances.Count); simpleInstances.Should().BeEquivalentTo(expected); } - + [Fact] public void MapInstanceListToSimpleInstanceList_Empty_LastChangedBy_When_Not_In_UserDict_Or_Unset() { @@ -58,11 +58,11 @@ public void MapInstanceListToSimpleInstanceList_Empty_LastChangedBy_When_Not_In_ new SimpleInstance { Id = "1", LastChanged = DateTime.Today, LastChangedBy = "" }, new SimpleInstance { Id = "2", LastChanged = DateTime.Today, LastChangedBy = "" } }; - + // Act var simpleInstances = SimpleInstanceMapper.MapInstanceListToSimpleInstanceList(instances, userDictionary); - + // Assert Assert.Equal(expected.Count, simpleInstances.Count); simpleInstances.Should().BeEquivalentTo(expected); diff --git a/test/Altinn.App.Api.Tests/Mocks/AppModelMock.cs b/test/Altinn.App.Api.Tests/Mocks/AppModelMock.cs index 54fcce581..e7caf6adf 100644 --- a/test/Altinn.App.Api.Tests/Mocks/AppModelMock.cs +++ b/test/Altinn.App.Api.Tests/Mocks/AppModelMock.cs @@ -3,7 +3,7 @@ namespace Altinn.App.Api.Tests.Mocks; -public class AppModelMock: IAppModel +public class AppModelMock : IAppModel { public object Create(string classRef) { diff --git a/test/Altinn.App.Api.Tests/Mocks/AuthorizationMock.cs b/test/Altinn.App.Api.Tests/Mocks/AuthorizationMock.cs index bc843ee9f..3f6059dde 100644 --- a/test/Altinn.App.Api.Tests/Mocks/AuthorizationMock.cs +++ b/test/Altinn.App.Api.Tests/Mocks/AuthorizationMock.cs @@ -33,7 +33,7 @@ public class AuthorizationMock : IAuthorizationClient public async Task AuthorizeAction(AppIdentifier appIdentifier, InstanceIdentifier instanceIdentifier, ClaimsPrincipal user, string action, string? taskId = null) { await Task.CompletedTask; - if(action.EndsWith("_unauthorized")) + if (action.EndsWith("_unauthorized")) { return false; } @@ -47,7 +47,7 @@ public async Task> AuthorizeActions(Instance instance, Dictionary authorizedActions = new Dictionary(); foreach (var action in actions) { - if(action.EndsWith("_unauthorized")) + if (action.EndsWith("_unauthorized")) { authorizedActions.Add(action, false); } diff --git a/test/Altinn.App.Api.Tests/Mocks/InstanceClientMockSi.cs b/test/Altinn.App.Api.Tests/Mocks/InstanceClientMockSi.cs index 99dc9d0e2..02495871b 100644 --- a/test/Altinn.App.Api.Tests/Mocks/InstanceClientMockSi.cs +++ b/test/Altinn.App.Api.Tests/Mocks/InstanceClientMockSi.cs @@ -47,7 +47,7 @@ public Task CreateInstance(string org, string app, Instance instanceTe File.WriteAllText(instancePath, instance.ToString()); _logger.LogInformation("Created instance for app {org}/{app}. writing to path: {instancePath}", org, app, instancePath); - + return Task.FromResult(instance); } @@ -65,15 +65,15 @@ public async Task GetInstance(Instance instance) public Task GetInstance(string app, string org, int instanceOwnerPartyId, Guid instanceId) { Instance instance = GetTestInstance(app, org, instanceOwnerPartyId, instanceId); - + if (instance is null) { throw new IOException($"Could not load instance {instanceId} from app {org}/{app}"); - } + } instance.Data = GetDataElements(org, app, instanceOwnerPartyId, instanceId); (instance.LastChangedBy, instance.LastChanged) = FindLastChanged(instance); - + return Task.FromResult(instance); } @@ -93,7 +93,7 @@ public Task UpdateProcess(Instance instance) string content = File.ReadAllText(instancePath); - Instance storedInstance = JsonConvert.DeserializeObject(content) ?? + Instance storedInstance = JsonConvert.DeserializeObject(content) ?? throw new InvalidDataException($"Something went wrong deserializing json for instance {instance.Id} from path {instancePath}"); // Archiving instance if process was ended @@ -121,9 +121,9 @@ private static Instance GetTestInstance(string app, string org, int instanceOwne } string content = File.ReadAllText(instancePath); - Instance instance = JsonConvert.DeserializeObject(content) ?? + Instance instance = JsonConvert.DeserializeObject(content) ?? throw new InvalidDataException($"Something went wrong deserializing json for instance from path {instancePath}"); - + return instance; } @@ -160,7 +160,7 @@ private List GetDataElements(string org, string app, int instanceOw { return dataElements; } - + foreach (string file in Directory.GetFiles(path)) { if (file.Contains(".pretest")) @@ -169,7 +169,7 @@ private List GetDataElements(string org, string app, int instanceOw } string content = File.ReadAllText(Path.Combine(path, file)); - DataElement dataElement = JsonConvert.DeserializeObject(content) ?? + DataElement dataElement = JsonConvert.DeserializeObject(content) ?? throw new InvalidDataException($"Something went wrong deserializing json for data from path {file}"); if (dataElement.DeleteStatus?.IsHardDeleted == true && string.IsNullOrEmpty(_httpContextAccessor?.HttpContext?.User?.GetOrg())) @@ -225,7 +225,7 @@ public async Task UpdateReadStatus(int instanceOwnerPartyId, Guid inst { throw new IOException($"Could not find file for instance on specified path {instancePath}."); } - + string content = File.ReadAllText(instancePath); Instance storedInstance = JsonConvert.DeserializeObject(content) ?? throw new InvalidDataException($"Something went wrong deserializing json for instance from path {instancePath}"); diff --git a/test/Altinn.App.Api.Tests/Program.cs b/test/Altinn.App.Api.Tests/Program.cs index 0a687b85c..2e9f0460b 100644 --- a/test/Altinn.App.Api.Tests/Program.cs +++ b/test/Altinn.App.Api.Tests/Program.cs @@ -79,4 +79,4 @@ void Configure() // This "hack" (documentet by Microsoft) is done to // make the Program class public and available for // integration tests. -public partial class Program {} +public partial class Program { } diff --git a/test/Altinn.App.Api.Tests/TestStubs/SwaggerIncludeXmlCommentsTestDouble.cs b/test/Altinn.App.Api.Tests/TestStubs/SwaggerIncludeXmlCommentsTestDouble.cs index 92e2ab092..d5a23f467 100644 --- a/test/Altinn.App.Api.Tests/TestStubs/SwaggerIncludeXmlCommentsTestDouble.cs +++ b/test/Altinn.App.Api.Tests/TestStubs/SwaggerIncludeXmlCommentsTestDouble.cs @@ -13,7 +13,7 @@ public void IncludeXmlCommentsTestDouble(string s, bool b) _strings.Add(s); _bools.Add(b); } - + public void IncludeXmlCommentsFailingTestDouble(string s, bool b) { throw new Exception("xUnit expected exception"); diff --git a/test/Altinn.App.Api.Tests/Utils/PrincipalUtil.cs b/test/Altinn.App.Api.Tests/Utils/PrincipalUtil.cs index 94280afcd..69d5f6f82 100644 --- a/test/Altinn.App.Api.Tests/Utils/PrincipalUtil.cs +++ b/test/Altinn.App.Api.Tests/Utils/PrincipalUtil.cs @@ -56,7 +56,7 @@ public static ClaimsPrincipal GetOrgPrincipal(string org, int authenticationLeve public static string GetOrgToken(string org, int authenticationLevel = 3) { - ClaimsPrincipal principal = GetOrgPrincipal(org, authenticationLevel); + ClaimsPrincipal principal = GetOrgPrincipal(org, authenticationLevel); return JwtTokenMock.GenerateToken(principal, new TimeSpan(1, 1, 1)); } diff --git a/test/Altinn.App.Core.Tests/DataLists/NullInstanceDataListProviderTest.cs b/test/Altinn.App.Core.Tests/DataLists/NullInstanceDataListProviderTest.cs index c59ca6cc4..67d3f173e 100644 --- a/test/Altinn.App.Core.Tests/DataLists/NullInstanceDataListProviderTest.cs +++ b/test/Altinn.App.Core.Tests/DataLists/NullInstanceDataListProviderTest.cs @@ -9,12 +9,13 @@ namespace Altinn.App.PlatformServices.Tests.DataLists public class NullInstanceDataListProviderTest { [Fact] - public void Constructor_InitializedWithEmptyValues() + public async void Constructor_InitializedWithEmptyValues() { var provider = new NullInstanceDataListProvider(); provider.Id.Should().Be(string.Empty); - provider.GetInstanceDataListAsync(new InstanceIdentifier(12345, Guid.NewGuid()), "nb", new Dictionary()).Result.ListItems.Should().BeNull(); + var options = await provider.GetInstanceDataListAsync(new InstanceIdentifier(12345, Guid.NewGuid()), "nb", new Dictionary()); + options.ListItems.Should().BeNull(); } } } diff --git a/test/Altinn.App.Core.Tests/Eformidling/Implementation/DefaultEFormidlingServiceTests.cs b/test/Altinn.App.Core.Tests/Eformidling/Implementation/DefaultEFormidlingServiceTests.cs index 5a3bad4de..841d9712c 100644 --- a/test/Altinn.App.Core.Tests/Eformidling/Implementation/DefaultEFormidlingServiceTests.cs +++ b/test/Altinn.App.Core.Tests/Eformidling/Implementation/DefaultEFormidlingServiceTests.cs @@ -73,9 +73,9 @@ public void SendEFormidlingShipment() eFormidlingReceivers.Setup(er => er.GetEFormidlingReceivers(instance)).ReturnsAsync(new List()); eFormidlingMetadata.Setup(em => em.GenerateEFormidlingMetadata(instance)).ReturnsAsync(() => { - return ("fakefilename.txt", Stream.Null); + return ("fakefilename.txt", Stream.Null); }); - + var defaultEformidlingService = new DefaultEFormidlingService( logger, userTokenProvider.Object, @@ -99,7 +99,7 @@ public void SendEFormidlingShipment() { 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()); @@ -109,17 +109,17 @@ public void SendEFormidlingShipment() 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() { @@ -170,11 +170,11 @@ public void SendEFormidlingShipment_throws_exception_if_send_fails() eFormidlingReceivers.Setup(er => er.GetEFormidlingReceivers(instance)).ReturnsAsync(new List()); eFormidlingMetadata.Setup(em => em.GenerateEFormidlingMetadata(instance)).ReturnsAsync(() => { - return ("fakefilename.txt", Stream.Null); + return ("fakefilename.txt", Stream.Null); }); eFormidlingClient.Setup(ec => ec.SendMessage(It.IsAny(), It.IsAny>())) .ThrowsAsync(new Exception("XUnit expected exception")); - + var defaultEformidlingService = new DefaultEFormidlingService( logger, userTokenProvider.Object, @@ -199,7 +199,7 @@ public void SendEFormidlingShipment_throws_exception_if_send_fails() { 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()); @@ -208,14 +208,14 @@ public void SendEFormidlingShipment_throws_exception_if_send_fails() eFormidlingClient.Verify(ec => ec.CreateMessage(It.IsAny(), 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(); } } \ No newline at end of file diff --git a/test/Altinn.App.Core.Tests/Extensions/DictionaryExtensionsTests.cs b/test/Altinn.App.Core.Tests/Extensions/DictionaryExtensionsTests.cs index dd7298272..197800bf9 100644 --- a/test/Altinn.App.Core.Tests/Extensions/DictionaryExtensionsTests.cs +++ b/test/Altinn.App.Core.Tests/Extensions/DictionaryExtensionsTests.cs @@ -74,7 +74,7 @@ public void ToNameValueString_OptionParametersWithSpecialCharaters_IsValidAsHead }; IHeaderDictionary headers = new HeaderDictionary(); - headers.Add("Altinn-DownstreamParameters", options.Parameters.ToUrlEncodedNameValueString(',')); + headers.Append("Altinn-DownstreamParameters", options.Parameters.ToUrlEncodedNameValueString(',')); Assert.Equal("lang=nb,level=1,name=%C3%86%C3%98%C3%85,variant=Sm%C3%A5vilt1", headers["Altinn-DownstreamParameters"]); } diff --git a/test/Altinn.App.Core.Tests/Extensions/ProcessStateExtensionTests.cs b/test/Altinn.App.Core.Tests/Extensions/ProcessStateExtensionTests.cs index 25d5a9a39..59a2e917f 100644 --- a/test/Altinn.App.Core.Tests/Extensions/ProcessStateExtensionTests.cs +++ b/test/Altinn.App.Core.Tests/Extensions/ProcessStateExtensionTests.cs @@ -47,7 +47,7 @@ public void Copy_returns_state_with_fields_set() Assert.Same(original.CurrentTask.Validated, copy.CurrentTask.Validated); copy.Should().BeEquivalentTo(original); } - + [Fact] public void Copy_returns_state_with_current_null_when_original_null() { diff --git a/test/Altinn.App.Core.Tests/Features/Action/SigningUserActionTests.cs b/test/Altinn.App.Core.Tests/Features/Action/SigningUserActionTests.cs index d4dcd6a8f..312647237 100644 --- a/test/Altinn.App.Core.Tests/Features/Action/SigningUserActionTests.cs +++ b/test/Altinn.App.Core.Tests/Features/Action/SigningUserActionTests.cs @@ -65,7 +65,7 @@ public async void HandleAction_returns_ok_if_user_is_valid() result.Should().BeEquivalentTo(UserActionResult.SuccessResult()); signClientMock.VerifyNoOtherCalls(); } - + [Fact] public async void HandleAction_throws_ApplicationConfigException_if_SignatureDataType_is_null() { @@ -105,11 +105,11 @@ public async void HandleAction_throws_ApplicationConfigException_if_SignatureDat await Assert.ThrowsAsync(async () => await userAction.HandleAction(userActionContext)); signClientMock.VerifyNoOtherCalls(); } - + private static (SigningUserAction SigningUserAction, Mock SignClientMock) CreateSigningUserAction(UserProfile userProfileToReturn = null, PlatformHttpException platformHttpExceptionToThrow = null, string testBpmnfilename = "signing-task-process.bpmn") { IProcessReader processReader = ProcessTestUtils.SetupProcessReader(testBpmnfilename, Path.Combine("Features", "Action", "TestData")); - + var profileClientMock = new Mock(); var signingClientMock = new Mock(); profileClientMock.Setup(p => p.GetUserProfile(It.IsAny())).ReturnsAsync(userProfileToReturn); @@ -117,7 +117,7 @@ private static (SigningUserAction SigningUserAction, Mock SignClien { signingClientMock.Setup(p => p.SignDataElements(It.IsAny())).ThrowsAsync(platformHttpExceptionToThrow); } - + return (new SigningUserAction(processReader, new NullLogger(), profileClientMock.Object, signingClientMock.Object), signingClientMock); } diff --git a/test/Altinn.App.Core.Tests/Features/Action/UniqueSignatureAuthorizerTests.cs b/test/Altinn.App.Core.Tests/Features/Action/UniqueSignatureAuthorizerTests.cs index bc3b5ec34..8f018af4d 100644 --- a/test/Altinn.App.Core.Tests/Features/Action/UniqueSignatureAuthorizerTests.cs +++ b/test/Altinn.App.Core.Tests/Features/Action/UniqueSignatureAuthorizerTests.cs @@ -41,7 +41,7 @@ public async Task AuthorizeAction_returns_true_if_uniqueFromSignaturesInDataType _processReaderMock.Verify(p => p.GetFlowElement("Task_2")); result.Should().BeTrue(); } - + [Fact] public async Task AuthorizeAction_returns_true_if_uniqueFromSignaturesInDataTypes_null() { @@ -77,7 +77,7 @@ public async Task AuthorizeAction_returns_true_if_SignatureConfiguration_is_null _processReaderMock.Verify(p => p.GetFlowElement("Task_2")); result.Should().BeTrue(); } - + [Fact] public async Task AuthorizeAction_returns_true_if_TaskExtension_is_null() { @@ -100,7 +100,7 @@ public async Task AuthorizeAction_returns_true_if_TaskExtension_is_null() _processReaderMock.Verify(p => p.GetFlowElement("Task_2")); result.Should().BeTrue(); } - + [Fact] public async Task AuthorizeAction_returns_true_if_other_user_has_signed_previously() { @@ -135,7 +135,7 @@ public async Task AuthorizeAction_returns_true_if_other_user_has_signed_previous _dataClientMock.Verify(d => d.GetBinaryData("ttd", "xunit-app", 500001, Guid.Parse("abba2e90-f86f-4881-b0e8-38334408bcb4"), Guid.Parse("ca62613c-f058-4899-b962-89dd6496a751"))); result.Should().BeTrue(); } - + [Fact] public async Task AuthorizeAction_returns_false_if_same_user_has_signed_previously() { @@ -170,7 +170,7 @@ public async Task AuthorizeAction_returns_false_if_same_user_has_signed_previous _dataClientMock.Verify(d => d.GetBinaryData("ttd", "xunit-app", 500001, Guid.Parse("abba2e90-f86f-4881-b0e8-38334408bcb4"), Guid.Parse("ca62613c-f058-4899-b962-89dd6496a751"))); result.Should().BeFalse(); } - + [Fact] public async Task AuthorizeAction_returns_true_if_taskID_is_null() { @@ -201,7 +201,7 @@ public async Task AuthorizeAction_returns_true_if_taskID_is_null() bool result = await authorizer.AuthorizeAction(new UserActionAuthorizerContext(user, new InstanceIdentifier("500001/abba2e90-f86f-4881-b0e8-38334408bcb4"), null, "sign")); result.Should().BeTrue(); } - + [Fact] public async Task AuthorizeAction_returns_true_if_dataelement_not_of_type_SignDocument() { @@ -236,7 +236,7 @@ public async Task AuthorizeAction_returns_true_if_dataelement_not_of_type_SignDo _dataClientMock.Verify(d => d.GetBinaryData("ttd", "xunit-app", 500001, Guid.Parse("abba2e90-f86f-4881-b0e8-38334408bcb4"), Guid.Parse("ca62613c-f058-4899-b962-89dd6496a751"))); result.Should().BeTrue(); } - + [Fact] public async Task AuthorizeAction_returns_true_if_signdumcument_is_missing_signee() { @@ -271,7 +271,7 @@ public async Task AuthorizeAction_returns_true_if_signdumcument_is_missing_signe _dataClientMock.Verify(d => d.GetBinaryData("ttd", "xunit-app", 500001, Guid.Parse("abba2e90-f86f-4881-b0e8-38334408bcb4"), Guid.Parse("ca62613c-f058-4899-b962-89dd6496a751"))); result.Should().BeTrue(); } - + [Fact] public async Task AuthorizeAction_returns_true_if_signdumcument_is_missing_signee_userid() { @@ -306,7 +306,7 @@ public async Task AuthorizeAction_returns_true_if_signdumcument_is_missing_signe _dataClientMock.Verify(d => d.GetBinaryData("ttd", "xunit-app", 500001, Guid.Parse("abba2e90-f86f-4881-b0e8-38334408bcb4"), Guid.Parse("ca62613c-f058-4899-b962-89dd6496a751"))); result.Should().BeTrue(); } - + [Fact] public async Task AuthorizeAction_returns_true_if_signdumcument_signee_userid_is_null() { diff --git a/test/Altinn.App.Core.Tests/Features/Action/UserActionServiceTests.cs b/test/Altinn.App.Core.Tests/Features/Action/UserActionServiceTests.cs index 0084a6dc1..d290e230c 100644 --- a/test/Altinn.App.Core.Tests/Features/Action/UserActionServiceTests.cs +++ b/test/Altinn.App.Core.Tests/Features/Action/UserActionServiceTests.cs @@ -19,7 +19,7 @@ public void GetActionHandlerOrDefault_should_return_DummyActionHandler_for_id_du userAction.Should().BeOfType(); userAction!.Id.Should().Be("dummy"); } - + [Fact] public void GetActionHandlerOrDefault_should_return_first_DummyActionHandler_for_id_dummy_if_multiple() { @@ -31,7 +31,7 @@ public void GetActionHandlerOrDefault_should_return_first_DummyActionHandler_for userAction.Should().BeOfType(); userAction!.Id.Should().Be("dummy"); } - + [Fact] public void GetActionHandlerOrDefault_should_return_null_if_id_not_found_and_default_not_set() { @@ -41,7 +41,7 @@ public void GetActionHandlerOrDefault_should_return_null_if_id_not_found_and_def userAction.Should().BeNull(); } - + [Fact] public void GetActionHandlerOrDefault_should_return_null_if_id_is_null_and_default_not_set() { @@ -51,7 +51,7 @@ public void GetActionHandlerOrDefault_should_return_null_if_id_is_null_and_defau userAction.Should().BeNull(); } - + internal class DummyUserAction : IUserAction { public string Id => "dummy"; @@ -61,7 +61,7 @@ public Task HandleAction(UserActionContext context) return Task.FromResult(UserActionResult.SuccessResult()); } } - + internal class DummyUserAction2 : IUserAction { public string Id => "dummy"; diff --git a/test/Altinn.App.Core.Tests/Features/DataProcessing/GenericDataProcessorTests.cs b/test/Altinn.App.Core.Tests/Features/DataProcessing/GenericDataProcessorTests.cs index 5a8e6ead3..b3c5f0446 100644 --- a/test/Altinn.App.Core.Tests/Features/DataProcessing/GenericDataProcessorTests.cs +++ b/test/Altinn.App.Core.Tests/Features/DataProcessing/GenericDataProcessorTests.cs @@ -39,7 +39,7 @@ public async Task ShouldRunForCorrectType() { var processor = new DummyProcessor(); var data = new DummyModel(); - await processor.ProcessDataRead(new Instance(), dataId: null, (object)data, language:null); + await processor.ProcessDataRead(new Instance(), dataId: null, (object)data, language: null); processor.ReadCalled.Should().BeTrue(); processor.WriteCalled.Should().BeFalse(); await processor.ProcessDataWrite(new Instance(), null, (object)data, null, null); @@ -52,7 +52,7 @@ public async Task ShouldNotRunForIncorrectType() { var processor = new DummyProcessor(); var data = new WrongModel(); - await processor.ProcessDataRead(new Instance(), dataId: null, (object)data, language:null); + await processor.ProcessDataRead(new Instance(), dataId: null, (object)data, language: null); processor.ReadCalled.Should().BeFalse(); processor.WriteCalled.Should().BeFalse(); await processor.ProcessDataWrite(new Instance(), null, (object)data, null, null); diff --git a/test/Altinn.App.Core.Tests/Features/Validators/Default/ExpressionValidatorTests.cs b/test/Altinn.App.Core.Tests/Features/Validators/Default/ExpressionValidatorTests.cs index ba22a06b0..a4d9997e5 100644 --- a/test/Altinn.App.Core.Tests/Features/Validators/Default/ExpressionValidatorTests.cs +++ b/test/Altinn.App.Core.Tests/Features/Validators/Default/ExpressionValidatorTests.cs @@ -98,7 +98,7 @@ public override IEnumerable GetData(MethodInfo methodInfo) { var files = Directory .GetFiles(Path.Join("Features", "Validators", "expression-validation-tests", "shared")) - .Concat( Directory.GetFiles(Path.Join("Features", "Validators", "expression-validation-tests", "backend"))); + .Concat(Directory.GetFiles(Path.Join("Features", "Validators", "expression-validation-tests", "backend"))); foreach (var file in files) { diff --git a/test/Altinn.App.Core.Tests/Features/Validators/ValidationServiceOldTests.cs b/test/Altinn.App.Core.Tests/Features/Validators/ValidationServiceOldTests.cs index bc1ce401f..a82db75c2 100644 --- a/test/Altinn.App.Core.Tests/Features/Validators/ValidationServiceOldTests.cs +++ b/test/Altinn.App.Core.Tests/Features/Validators/ValidationServiceOldTests.cs @@ -61,7 +61,7 @@ public async Task FileScanEnabled_VirusFound_ValidationShouldFail() var instance = new Instance(); var dataType = new DataType() { EnableFileScan = true }; - var dataElement = new DataElement() + var dataElement = new DataElement() { DataType = "test", FileScanResult = FileScanResult.Infected @@ -79,7 +79,7 @@ public async Task FileScanEnabled_PendingScanNotEnabled_ValidationShouldNotFail( IValidationService validationService = serviceProvider.GetRequiredService(); var dataType = new DataType() - { Id = "test", TaskId = "Task_1", AppLogic = null, EnableFileScan = true }; + { Id = "test", TaskId = "Task_1", AppLogic = null, EnableFileScan = true }; var instance = new Instance() { }; @@ -264,13 +264,13 @@ public void ModelKeyToField_StringInput_ReturnsSameString() { ModelStateHelpers.ModelKeyToField("null", typeof(TestModel)).Should().Be("null"); } - + [Fact] public void ModelKeyToField_StringInputWithAttr_ReturnsMappedString() { ModelStateHelpers.ModelKeyToField("FirstLevelProp", typeof(TestModel)).Should().Be("level1"); } - + [Fact] public void ModelKeyToField_SubModel_ReturnsMappedString() { diff --git a/test/Altinn.App.Core.Tests/Helpers/JsonDataModel.cs b/test/Altinn.App.Core.Tests/Helpers/JsonDataModel.cs index 1ea5c9392..f36d4c5b4 100644 --- a/test/Altinn.App.Core.Tests/Helpers/JsonDataModel.cs +++ b/test/Altinn.App.Core.Tests/Helpers/JsonDataModel.cs @@ -200,7 +200,6 @@ private string[] GetResolvedKeysRecursive(string[] keyParts, JsonNode? currentMo // Otherwise, just recurse return GetResolvedKeysRecursive(keyParts, childModel, currentIndex + 1, DataModel.JoinFieldKeyParts(currentKey, key)); - } /// @@ -292,7 +291,6 @@ public void RemoveField(string key, RowRemovalOption rowRemovalOption) // Set the property to null containingObject[lastKey] = null; } - } /// diff --git a/test/Altinn.App.Core.Tests/Helpers/JsonHelperTests.cs b/test/Altinn.App.Core.Tests/Helpers/JsonHelperTests.cs index 4f5bd80f0..6555fb392 100644 --- a/test/Altinn.App.Core.Tests/Helpers/JsonHelperTests.cs +++ b/test/Altinn.App.Core.Tests/Helpers/JsonHelperTests.cs @@ -26,7 +26,7 @@ public class JsonHelperTests .Setup((d) => d.ProcessDataWrite(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), null)) .Returns(dataProcessWrite); - return await JsonHelper.ProcessDataWriteWithDiff(instance, guid, model, language:null, new IDataProcessor[] { dataProcessorMock.Object }, logger); + return await JsonHelper.ProcessDataWriteWithDiff(instance, guid, model, language: null, new IDataProcessor[] { dataProcessorMock.Object }, logger); } public class TestModel diff --git a/test/Altinn.App.Core.Tests/Helpers/MimeTypeMapTests.cs b/test/Altinn.App.Core.Tests/Helpers/MimeTypeMapTests.cs index 377f22219..f908e8334 100644 --- a/test/Altinn.App.Core.Tests/Helpers/MimeTypeMapTests.cs +++ b/test/Altinn.App.Core.Tests/Helpers/MimeTypeMapTests.cs @@ -68,7 +68,7 @@ public void GetMimeType_throws_ArgumentNullException_if_extension_null() Action act = () => MimeTypeMap.GetMimeType(null); act.Should().Throw(); } - + [Fact] public void GetMimeType_returns_octetstream_for_unknown_fileextension() { diff --git a/test/Altinn.App.Core.Tests/Helpers/MultiDecisionHelperTests.cs b/test/Altinn.App.Core.Tests/Helpers/MultiDecisionHelperTests.cs index f19e27a3e..598d63deb 100644 --- a/test/Altinn.App.Core.Tests/Helpers/MultiDecisionHelperTests.cs +++ b/test/Altinn.App.Core.Tests/Helpers/MultiDecisionHelperTests.cs @@ -11,11 +11,11 @@ namespace Altinn.App.Core.Tests.Helpers; public class MultiDecisionHelperTests { - private static readonly JsonSerializerOptions SerializerOptions = new() + private static readonly JsonSerializerOptions SerializerOptions = new() { WriteIndented = true }; - + [Fact] public void CreateMultiDecisionRequest_generates_multidecisionrequest_with_all_actions_current_task_elemtnId() { @@ -48,10 +48,10 @@ public void CreateMultiDecisionRequest_generates_multidecisionrequest_with_all_a }; var result = MultiDecisionHelper.CreateMultiDecisionRequest(claimsPrincipal, instance, actions); - + CompareWithOrUpdateGoldenFile("multidecision-all-actions-task", result); } - + [Fact] public void CreateMultiDecisionRequest_generates_multidecisionrequest_with_all_actions_instanceId_is_GUID_only() { @@ -84,10 +84,10 @@ public void CreateMultiDecisionRequest_generates_multidecisionrequest_with_all_a }; var result = MultiDecisionHelper.CreateMultiDecisionRequest(claimsPrincipal, instance, actions); - + CompareWithOrUpdateGoldenFile("multidecision-all-actions-guid", result); } - + [Fact] public void CreateMultiDecisionRequest_generates_multidecisionrequest_with_all_actions_endevent() { @@ -119,10 +119,10 @@ public void CreateMultiDecisionRequest_generates_multidecisionrequest_with_all_a }; var result = MultiDecisionHelper.CreateMultiDecisionRequest(claimsPrincipal, instance, actions); - + CompareWithOrUpdateGoldenFile("multidecision-all-actions-endevent", result); } - + [Fact] public void CreateMultiDecisionRequest_throws_ArgumentNullException_if_user_is_null() { @@ -175,7 +175,7 @@ public void ValidateDecisionResult_all_actions_allowed() var result = MultiDecisionHelper.ValidatePdpMultiDecision(actions, response, GetClaims("501337")); result.Should().BeEquivalentTo(expected); } - + [Fact] public void ValidateDecisionResult_one_action_denied() { @@ -197,7 +197,7 @@ public void ValidateDecisionResult_one_action_denied() var result = MultiDecisionHelper.ValidatePdpMultiDecision(actions, response, GetClaims("501337")); result.Should().BeEquivalentTo(expected); } - + [Fact] public void ValidateDecisionResult_throws_ArgumentNullException_if_response_is_null() { @@ -211,7 +211,7 @@ public void ValidateDecisionResult_throws_ArgumentNullException_if_response_is_n Action act = () => MultiDecisionHelper.ValidatePdpMultiDecision(actions, null, GetClaims("501337")); act.Should().Throw().WithMessage("Value cannot be null. (Parameter 'results')"); } - + [Fact] public void ValidateDecisionResult_throws_ArgumentNullException_if_user_is_null() { diff --git a/test/Altinn.App.Core.Tests/Helpers/ProcessHelperTests.cs b/test/Altinn.App.Core.Tests/Helpers/ProcessHelperTests.cs index 4f042f897..9bb225007 100644 --- a/test/Altinn.App.Core.Tests/Helpers/ProcessHelperTests.cs +++ b/test/Altinn.App.Core.Tests/Helpers/ProcessHelperTests.cs @@ -12,7 +12,7 @@ namespace Altinn.App.PlatformServices.Tests.Helpers; public class ProcessHelperTests { [Fact] - public void CanEndProcessTask_returns_true_when_task_is_validated_even_with_validationIssues() + public async Task CanEndProcessTask_returns_true_when_task_is_validated_even_with_validationIssues() { // Arrange var instance = new Instance() @@ -37,22 +37,24 @@ public void CanEndProcessTask_returns_true_when_task_is_validated_even_with_vali }; // Act and Assert - ProcessHelper.CanEndProcessTask(instance, validationIssues).Result.Should().BeTrue(); + var canEnd = await ProcessHelper.CanEndProcessTask(instance, validationIssues); + canEnd.Should().BeTrue(); } [Fact] - public void CanEndProcessTask_returns_true_when_no_validationIssues() + public async Task CanEndProcessTask_returns_true_when_no_validationIssues() { // Arrange var instance = new Instance(); var validationIssues = new List(); // Act and Assert - ProcessHelper.CanEndProcessTask(instance, validationIssues).Result.Should().BeTrue(); + var canEnd = await ProcessHelper.CanEndProcessTask(instance, validationIssues); + canEnd.Should().BeTrue(); } [Fact] - public void CanEndProcessTask_returns_false_when_task_is_validated_false_even_with_no_validationIssues() + public async void CanEndProcessTask_returns_false_when_task_is_validated_false_even_with_no_validationIssues() { // Arrange var instance = new Instance() @@ -71,11 +73,12 @@ public void CanEndProcessTask_returns_false_when_task_is_validated_false_even_wi var validationIssues = new List(); // Act and Assert - ProcessHelper.CanEndProcessTask(instance, validationIssues).Result.Should().BeFalse(); + var canEnd = await ProcessHelper.CanEndProcessTask(instance, validationIssues); + canEnd.Should().BeFalse(); } [Fact] - public void CanEndProcessTask_returns_false_when_task_is_not_validated_with_validationIssues() + public async void CanEndProcessTask_returns_false_when_task_is_not_validated_with_validationIssues() { // Arrange var instance = new Instance(); @@ -88,7 +91,8 @@ public void CanEndProcessTask_returns_false_when_task_is_not_validated_with_vali }; // Act and Assert - ProcessHelper.CanEndProcessTask(instance, validationIssues).Result.Should().BeFalse(); + var canEnd = await ProcessHelper.CanEndProcessTask(instance, validationIssues); + canEnd.Should().BeFalse(); } [Fact] @@ -233,7 +237,7 @@ public void GetSequenceFlowType_returns_flowtype_of_first_SequenceFlow() }; ProcessHelper.GetSequenceFlowType(sequenceFlows).Should().Be(ProcessSequenceFlowType.AbandonCurrentReturnToNext); } - + [Fact] public void GetSequenceFlowType_returns_second_flow_type_if_FlowType_Not_Defined_on_first_flow() { @@ -255,7 +259,7 @@ public void GetSequenceFlowType_returns_second_flow_type_if_FlowType_Not_Defined }; ProcessHelper.GetSequenceFlowType(sequenceFlows).Should().Be(ProcessSequenceFlowType.AbandonCurrentReturnToNext); } - + [Fact] public void GetSequenceFlowType_returns_CompleteCurrentMoveToNext_if_FlowType_Not_Defined() { @@ -276,7 +280,7 @@ public void GetSequenceFlowType_returns_CompleteCurrentMoveToNext_if_FlowType_No }; ProcessHelper.GetSequenceFlowType(sequenceFlows).Should().Be(ProcessSequenceFlowType.CompleteCurrentMoveToNext); } - + [Fact] public void GetSequenceFlowType_returns_CompleteCurrentMoveToNext_if_Unknown_FlowTypes() { diff --git a/test/Altinn.App.Core.Tests/Helpers/RemoveBomExtentionsTests.cs b/test/Altinn.App.Core.Tests/Helpers/RemoveBomExtentionsTests.cs index 5c7109002..aafebdb62 100644 --- a/test/Altinn.App.Core.Tests/Helpers/RemoveBomExtentionsTests.cs +++ b/test/Altinn.App.Core.Tests/Helpers/RemoveBomExtentionsTests.cs @@ -14,7 +14,7 @@ public void TestRemoveBom() withBom.RemoveBom().ToArray().Should().HaveCount(withBom.Length - 3); } - + [Fact] public void TestNotRemoveBom() { diff --git a/test/Altinn.App.Core.Tests/Helpers/ShadowFieldsConverterTests.cs b/test/Altinn.App.Core.Tests/Helpers/ShadowFieldsConverterTests.cs index 955cd0a86..a10b24b41 100644 --- a/test/Altinn.App.Core.Tests/Helpers/ShadowFieldsConverterTests.cs +++ b/test/Altinn.App.Core.Tests/Helpers/ShadowFieldsConverterTests.cs @@ -53,7 +53,7 @@ public void ShouldRemoveShadowFields_WithPrefix() }, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, }; - + // Check that serialization with modifier removes shadow fields from result string serializedData = JsonSerializer.Serialize(data, options); Assert.DoesNotContain("AltinnSF_", serializedData); diff --git a/test/Altinn.App.Core.Tests/Implementation/AppResourcesSITests.cs b/test/Altinn.App.Core.Tests/Implementation/AppResourcesSITests.cs index b592d3640..a3a5af28e 100644 --- a/test/Altinn.App.Core.Tests/Implementation/AppResourcesSITests.cs +++ b/test/Altinn.App.Core.Tests/Implementation/AppResourcesSITests.cs @@ -67,7 +67,7 @@ public void GetApplication_desrializes_file_from_disk() actual.Should().NotBeNull(); actual.Should().BeEquivalentTo(expected); } - + [Fact] public void GetApplication_handles_onEntry_null() { diff --git a/test/Altinn.App.Core.Tests/Implementation/DefaultTaskEventsTests.cs b/test/Altinn.App.Core.Tests/Implementation/DefaultTaskEventsTests.cs index 89d65e2b0..9590d9254 100644 --- a/test/Altinn.App.Core.Tests/Implementation/DefaultTaskEventsTests.cs +++ b/test/Altinn.App.Core.Tests/Implementation/DefaultTaskEventsTests.cs @@ -20,7 +20,7 @@ namespace Altinn.App.PlatformServices.Tests.Implementation; -public class DefaultTaskEventsTests: IDisposable +public class DefaultTaskEventsTests : IDisposable { private readonly ILogger _logger = NullLogger.Instance; private readonly Mock _resMock; @@ -76,7 +76,7 @@ public async void OnAbandonProcessTask_handles_no_IProcessTaskAbandon_injected() _layoutStateInitializer); await te.OnAbandonProcessTask("Task_1", new Instance()); } - + [Fact] public async void OnAbandonProcessTask_calls_all_added_implementations() { @@ -278,7 +278,7 @@ public async void OnEndProcessTask_throws_exception_when_saveToDataType_is_speci AppId = "ttd/shadow-fields-test", Data = new List() { - { + { new() { DataType = "model", @@ -319,7 +319,7 @@ public async void OnEndProcessTask_throws_exception_when_saveToDataType_is_speci _metaMock.Verify(r => r.GetApplicationMetadata()); _dataMock.Verify(r => r.GetFormData(instanceGuid, modelType, "ttd", "shadow-fields-test", 1000, dataElementId)); } - + [Fact] public async void OnEndProcessTask_calls_all_added_implementations_of_IProcessTaskStart() { @@ -399,7 +399,7 @@ public async void OnEndProcessTask_does_not_sets_hard_soft_delete_if_process_end _metaMock.Verify(r => r.GetApplicationMetadata()); _instanceMock.Verify(i => i.DeleteInstance(1000, Guid.Parse("fa0678ad-960d-4307-aba2-ba29c9804c9d"), true), Times.Never); } - + [Fact] public async void OnEndProcessTask_deletes_old_datatypes_generated_from_task_beeing_ended() { @@ -467,7 +467,7 @@ public async void OnEndProcessTask_deletes_old_datatypes_generated_from_task_bee _instanceMock.Verify(i => i.DeleteInstance(1000, Guid.Parse("fa0678ad-960d-4307-aba2-ba29c9804c9d"), true), Times.Never); _dataMock.Verify(d => d.DeleteData("ttd", "test", 1337, Guid.Parse("fa0678ad-960d-4307-aba2-ba29c9804c9d"), Guid.Parse("ba0678ad-960d-4307-aba2-ba29c9804c9d"), false), Times.Once); } - + [Fact] public async void OnEndProcessTask_sets_hard_soft_delete_if_process_ended_and_autoDeleteOnProcessEnd_true() { @@ -506,7 +506,7 @@ public async void OnEndProcessTask_sets_hard_soft_delete_if_process_ended_and_au _metaMock.Verify(r => r.GetApplicationMetadata()); _instanceMock.Verify(i => i.DeleteInstance(1000, Guid.Parse("fa0678ad-960d-4307-aba2-ba29c9804c9d"), true), Times.Once); } - + [Fact] public async void OnEndProcessTask_does_not_sets_hard_soft_delete_if_process_not_ended_and_autoDeleteOnProcessEnd_true() { @@ -530,7 +530,7 @@ public async void OnEndProcessTask_does_not_sets_hard_soft_delete_if_process_not var instance = new Instance() { Id = "1337/fa0678ad-960d-4307-aba2-ba29c9804c9d", - AppId = "ttd/test", + AppId = "ttd/test", InstanceOwner = new() { PartyId = "1000" @@ -542,7 +542,7 @@ public async void OnEndProcessTask_does_not_sets_hard_soft_delete_if_process_not _metaMock.Verify(r => r.GetApplicationMetadata()); _instanceMock.Verify(i => i.DeleteInstance(1000, Guid.Parse("fa0678ad-960d-4307-aba2-ba29c9804c9d"), true), Times.Never); } - + [Fact] public async void OnEndProcessTask_does_not_sets_hard_soft_delete_if_process_null_and_autoDeleteOnProcessEnd_true() { @@ -663,7 +663,7 @@ private ApplicationMetadata GetApplicationMetadataForShadowFields(bool useSaveTo private ModelWithShadowFields GetDataElementForShadowFields() { - return new ModelWithShadowFields() + return new ModelWithShadowFields() { AltinnSF_hello = "hello", AltinnSF_test = "test", diff --git a/test/Altinn.App.Core.Tests/Implementation/NullPdfFormatterTests.cs b/test/Altinn.App.Core.Tests/Implementation/NullPdfFormatterTests.cs index c43b40c03..da58fb6a8 100644 --- a/test/Altinn.App.Core.Tests/Implementation/NullPdfFormatterTests.cs +++ b/test/Altinn.App.Core.Tests/Implementation/NullPdfFormatterTests.cs @@ -35,12 +35,12 @@ public async void NullPdfFormatter_FormatPdf_returns_Layoutsettings_as_is() } } }; - + var nullPdfFormatter = new NullPdfFormatter(); - + // Act var result = await nullPdfFormatter.FormatPdf(layoutSettings, new DummyModel()); - + // Assert result.Should().BeEquivalentTo(layoutSettings); } diff --git a/test/Altinn.App.Core.Tests/Implementation/TestData/AppDataModel/ModelWithShadowFields.cs b/test/Altinn.App.Core.Tests/Implementation/TestData/AppDataModel/ModelWithShadowFields.cs index 5ea52ed16..5ff44476f 100644 --- a/test/Altinn.App.Core.Tests/Implementation/TestData/AppDataModel/ModelWithShadowFields.cs +++ b/test/Altinn.App.Core.Tests/Implementation/TestData/AppDataModel/ModelWithShadowFields.cs @@ -6,72 +6,72 @@ namespace Altinn.App.Core.Tests.Implementation.TestData.AppDataModel { - [XmlRoot(ElementName="model")] - public class ModelWithShadowFields - { - [Range(double.MinValue, double.MaxValue)] - [XmlElement("property1", Order = 1)] - [JsonProperty("property1")] - [JsonPropertyName("property1")] - [Required] - public decimal? Property1 { get; set; } + [XmlRoot(ElementName = "model")] + public class ModelWithShadowFields + { + [Range(double.MinValue, double.MaxValue)] + [XmlElement("property1", Order = 1)] + [JsonProperty("property1")] + [JsonPropertyName("property1")] + [Required] + public decimal? Property1 { get; set; } - [Range(double.MinValue, double.MaxValue)] - [XmlElement("property2", Order = 2)] - [JsonProperty("property2")] - [JsonPropertyName("property2")] - [Required] - public decimal? Property2 { get; set; } + [Range(double.MinValue, double.MaxValue)] + [XmlElement("property2", Order = 2)] + [JsonProperty("property2")] + [JsonPropertyName("property2")] + [Required] + public decimal? Property2 { get; set; } - [XmlElement("property3", Order = 3)] - [JsonProperty("property3")] - [JsonPropertyName("property3")] - public string Property3 { get; set; } + [XmlElement("property3", Order = 3)] + [JsonProperty("property3")] + [JsonPropertyName("property3")] + public string Property3 { get; set; } - [XmlElement("AltinnSF_hello", Order = 4)] - [JsonProperty("AltinnSF_hello")] - [JsonPropertyName("AltinnSF_hello")] - public string AltinnSF_hello { get; set; } + [XmlElement("AltinnSF_hello", Order = 4)] + [JsonProperty("AltinnSF_hello")] + [JsonPropertyName("AltinnSF_hello")] + public string AltinnSF_hello { get; set; } - [XmlElement("AltinnSF_test", Order = 5)] - [JsonProperty("AltinnSF_test")] - [JsonPropertyName("AltinnSF_test")] - public string AltinnSF_test { get; set; } + [XmlElement("AltinnSF_test", Order = 5)] + [JsonProperty("AltinnSF_test")] + [JsonPropertyName("AltinnSF_test")] + public string AltinnSF_test { get; set; } - [XmlElement("AltinnSF_gruppeish", Order = 6)] - [JsonProperty("AltinnSF_gruppeish")] - [JsonPropertyName("AltinnSF_gruppeish")] - public AltinnSF_gruppeish AltinnSF_gruppeish { get; set; } + [XmlElement("AltinnSF_gruppeish", Order = 6)] + [JsonProperty("AltinnSF_gruppeish")] + [JsonPropertyName("AltinnSF_gruppeish")] + public AltinnSF_gruppeish AltinnSF_gruppeish { get; set; } - [XmlElement("gruppe", Order = 7)] - [JsonProperty("gruppe")] - [JsonPropertyName("gruppe")] - public List Gruppe { get; set; } - } + [XmlElement("gruppe", Order = 7)] + [JsonProperty("gruppe")] + [JsonPropertyName("gruppe")] + public List Gruppe { get; set; } + } - public class AltinnSF_gruppeish - { - [XmlElement("f1", Order = 1)] - [JsonProperty("f1")] - [JsonPropertyName("f1")] - public string F1 { get; set; } + public class AltinnSF_gruppeish + { + [XmlElement("f1", Order = 1)] + [JsonProperty("f1")] + [JsonPropertyName("f1")] + public string F1 { get; set; } - [XmlElement("f2", Order = 2)] - [JsonProperty("f2")] - [JsonPropertyName("f2")] - public string F2 { get; set; } - } + [XmlElement("f2", Order = 2)] + [JsonProperty("f2")] + [JsonPropertyName("f2")] + public string F2 { get; set; } + } - public class Gruppe - { - [XmlElement("gf1", Order = 1)] - [JsonProperty("gf1")] - [JsonPropertyName("gf1")] - public string Gf1 { get; set; } + public class Gruppe + { + [XmlElement("gf1", Order = 1)] + [JsonProperty("gf1")] + [JsonPropertyName("gf1")] + public string Gf1 { get; set; } - [XmlElement("AltinnSF_gf-hjelpefelt", Order = 2)] - [JsonProperty("AltinnSF_gf-hjelpefelt")] - [JsonPropertyName("AltinnSF_gf-hjelpefelt")] - public string AltinnSF_gfhjelpefelt { get; set; } - } + [XmlElement("AltinnSF_gf-hjelpefelt", Order = 2)] + [JsonProperty("AltinnSF_gf-hjelpefelt")] + [JsonPropertyName("AltinnSF_gf-hjelpefelt")] + public string AltinnSF_gfhjelpefelt { get; set; } + } } diff --git a/test/Altinn.App.Core.Tests/Infrastructure/Clients/Authorization/AuthorizationClientTests.cs b/test/Altinn.App.Core.Tests/Infrastructure/Clients/Authorization/AuthorizationClientTests.cs index e53dda875..648eed05a 100644 --- a/test/Altinn.App.Core.Tests/Infrastructure/Clients/Authorization/AuthorizationClientTests.cs +++ b/test/Altinn.App.Core.Tests/Infrastructure/Clients/Authorization/AuthorizationClientTests.cs @@ -27,7 +27,7 @@ public async Task AuthorizeActions_returns_dictionary_with_one_action_denied() var pdpResponse = GetXacmlJsonRespons("one-action-denied"); pdpMock.Setup(s => s.GetDecisionForRequest(It.IsAny())).ReturnsAsync(pdpResponse); AuthorizationClient client = new AuthorizationClient(Options.Create(new PlatformSettings()), httpContextAccessorMock.Object, httpClientMock.Object, appSettingsMock.Object, pdpMock.Object, NullLogger.Instance); - + var claimsPrincipal = GetClaims("1337"); var instance = new Instance() @@ -49,7 +49,7 @@ public async Task AuthorizeActions_returns_dictionary_with_one_action_denied() EndEvent = "EndEvent_1" } }; - + var expected = new Dictionary() { { "read", true }, @@ -67,7 +67,7 @@ public async Task AuthorizeActions_returns_dictionary_with_one_action_denied() var actual = await client.AuthorizeActions(instance, claimsPrincipal, actions); actual.Should().BeEquivalentTo(expected); } - + [Fact] public async Task AuthorizeActions_returns_empty_dictionary_if_no_response_from_pdp() { @@ -77,7 +77,7 @@ public async Task AuthorizeActions_returns_empty_dictionary_if_no_response_from_ Mock> appSettingsMock = new(); pdpMock.Setup(s => s.GetDecisionForRequest(It.IsAny())).ReturnsAsync(new XacmlJsonResponse()); AuthorizationClient client = new AuthorizationClient(Options.Create(new PlatformSettings()), httpContextAccessorMock.Object, httpClientMock.Object, appSettingsMock.Object, pdpMock.Object, NullLogger.Instance); - + var claimsPrincipal = GetClaims("1337"); var instance = new Instance() @@ -99,7 +99,7 @@ public async Task AuthorizeActions_returns_empty_dictionary_if_no_response_from_ EndEvent = "EndEvent_1" } }; - + var expected = new Dictionary(); var actions = new List() { @@ -111,7 +111,7 @@ public async Task AuthorizeActions_returns_empty_dictionary_if_no_response_from_ var actual = await client.AuthorizeActions(instance, claimsPrincipal, actions); actual.Should().BeEquivalentTo(expected); } - + private static ClaimsPrincipal GetClaims(string partyId) { return new ClaimsPrincipal(new List() @@ -123,7 +123,7 @@ private static ClaimsPrincipal GetClaims(string partyId) }) }); } - + private static XacmlJsonResponse GetXacmlJsonRespons(string filename) { var xacmlJesonRespons = File.ReadAllText(Path.Join("Infrastructure", "Clients", "Authorization", "TestData", $"{filename}.json")); diff --git a/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/DataClientTests.cs b/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/DataClientTests.cs index b087826b4..7b30209da 100644 --- a/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/DataClientTests.cs +++ b/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/DataClientTests.cs @@ -70,7 +70,7 @@ public async Task InsertBinaryData_MethodProduceValidPlatformRequest() Assert.NotNull(platformRequest); AssertHttpRequest(platformRequest, expectedUri, HttpMethod.Post, "\"a cats story.pdf\"", "application/pdf"); } - + [Fact] public async Task InsertBinaryData_MethodProduceValidPlatformRequest_with_generatedFrom_query_params() { @@ -317,7 +317,7 @@ public async Task GetBinaryDataList_returns_AttachemtList_when_DataElements_foun await Task.CompletedTask; return new HttpResponseMessage() - { Content = new StringContent("{\"dataElements\":[{\"Id\":\"aaaa-bbbb-cccc-dddd\",\"Size\":10,\"DataType\":\"cats\"},{\"Id\":\"eeee-ffff-gggg-hhhh\", \"Size\":20,\"DataType\":\"dogs\"}]}") }; + { Content = new StringContent("{\"dataElements\":[{\"Id\":\"aaaa-bbbb-cccc-dddd\",\"Size\":10,\"DataType\":\"cats\"},{\"Id\":\"eeee-ffff-gggg-hhhh\", \"Size\":20,\"DataType\":\"dogs\"}]}") }; }); var expectedUri = new Uri($"{apiStorageEndpoint}instances/{instanceIdentifier}/dataelements", UriKind.RelativeOrAbsolute); var response = await dataClient.GetBinaryDataList("ttd", "app", instanceIdentifier.InstanceOwnerPartyId, instanceIdentifier.InstanceGuid); diff --git a/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/SignClientTests.cs b/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/SignClientTests.cs index 907e0363a..eb095924f 100644 --- a/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/SignClientTests.cs +++ b/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/SignClientTests.cs @@ -79,7 +79,7 @@ public async Task SignDataElements_sends_request_to_platform() }, SignatureDocumentDataType = "sign-data-type" }; - + await signClient.SignDataElements(signatureContext); // Assert @@ -91,7 +91,7 @@ public async Task SignDataElements_sends_request_to_platform() SignRequest actual = await JsonSerializerPermissive.DeserializeAsync(platformRequest!.Content!); actual.Should().BeEquivalentTo(expectedRequest); } - + [Fact] public async Task SignDataElements_throws_PlatformHttpException_if_platform_returns_http_errorcode() { @@ -120,8 +120,8 @@ public async Task SignDataElements_throws_PlatformHttpException_if_platform_retu PersonNumber = "0101011337" }, new DataElementSignature(dataElementId)); - - var ex = await Assert.ThrowsAsync(async() => await signClient.SignDataElements(signatureContext)); + + var ex = await Assert.ThrowsAsync(async () => await signClient.SignDataElements(signatureContext)); ex.Should().NotBeNull(); ex.Response.Should().NotBeNull(); ex.Response.StatusCode.Should().Be(HttpStatusCode.InternalServerError); diff --git a/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/TestData/ExampleModel.cs b/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/TestData/ExampleModel.cs index 1e6b09759..46f55c0bc 100644 --- a/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/TestData/ExampleModel.cs +++ b/test/Altinn.App.Core.Tests/Infrastructure/Clients/Storage/TestData/ExampleModel.cs @@ -10,7 +10,7 @@ public class ExampleModel /// The name /// public string Name { get; set; } = string.Empty; - + /// /// The age /// diff --git a/test/Altinn.App.Core.Tests/Internal/App/AppMedataTest.cs b/test/Altinn.App.Core.Tests/Internal/App/AppMedataTest.cs index 1b1167bd8..008883016 100644 --- a/test/Altinn.App.Core.Tests/Internal/App/AppMedataTest.cs +++ b/test/Altinn.App.Core.Tests/Internal/App/AppMedataTest.cs @@ -475,7 +475,7 @@ public async Task GetApplicationMetadata_deserializes_unmapped_properties() actual.UnmappedProperties!["foo"].Should().BeOfType(); ((JsonElement)actual.UnmappedProperties["foo"]).GetProperty("bar").GetString().Should().Be("baz"); } - + [Fact] public async Task GetApplicationMetadata_deserialize_serialize_unmapped_properties() { diff --git a/test/Altinn.App.Core.Tests/Internal/Events/EventHandlerResolverTests.cs b/test/Altinn.App.Core.Tests/Internal/Events/EventHandlerResolverTests.cs index 017c504cb..92b6736c8 100644 --- a/test/Altinn.App.Core.Tests/Internal/Events/EventHandlerResolverTests.cs +++ b/test/Altinn.App.Core.Tests/Internal/Events/EventHandlerResolverTests.cs @@ -11,7 +11,7 @@ namespace Altinn.App.PlatformServices.Tests.Internal.Events public class EventHandlerResolverTests { [Fact] - public void ResolveEventHandler_SubscriptionValidationHandler_ShouldReturnSubscriptionValidationHandler() + public async void ResolveEventHandler_SubscriptionValidationHandler_ShouldReturnSubscriptionValidationHandler() { var factory = new EventHandlerResolver(new List() { new SubscriptionValidationHandler() }); @@ -19,7 +19,8 @@ public void ResolveEventHandler_SubscriptionValidationHandler_ShouldReturnSubscr eventHandler.Should().BeOfType(); eventHandler.EventType.Should().Be("platform.events.validatesubscription"); - eventHandler.ProcessEvent(new CloudEvent()).Result.Should().BeTrue(); + var success = await eventHandler.ProcessEvent(new CloudEvent()); + success.Should().BeTrue(); } [Fact] @@ -29,7 +30,7 @@ public void ResolveEventHandler_InvalidEventType_ShouldReturnUnhandledEventHandl IEventHandler eventHandler = factory.ResolveEventHandler("this.event.should.not.exists"); Action action = () => eventHandler.ProcessEvent(new CloudEvent()); - + eventHandler.Should().BeOfType(); eventHandler.EventType.Should().Be("app.events.unhandled"); action.Should().Throw(); diff --git a/test/Altinn.App.Core.Tests/Internal/Patch/PatchServiceTests.cs b/test/Altinn.App.Core.Tests/Internal/Patch/PatchServiceTests.cs index d8f0a7a19..6b0f496b7 100644 --- a/test/Altinn.App.Core.Tests/Internal/Patch/PatchServiceTests.cs +++ b/test/Altinn.App.Core.Tests/Internal/Patch/PatchServiceTests.cs @@ -20,7 +20,7 @@ namespace Altinn.App.Core.Tests.Internal.Patch; public class PatchServiceTests { - // Test data + // Test data private static readonly Guid DataGuid = new("12345678-1234-1234-1234-123456789123"); private readonly Instance _instance = new() @@ -129,7 +129,7 @@ public async Task Test_Ok() issue.Description.Should().Be("First error"); _dataProcessorMock.Verify(d => d.ProcessDataWrite(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), null)); } - + [Fact] public async Task Test_JsonPatchTest_fail() { @@ -168,7 +168,7 @@ public async Task Test_JsonPatchTest_fail() err.Extensions.Should().ContainKey("previousModel"); err.Extensions.Should().ContainKey("patchOperationIndex"); } - + [Fact] public async Task Test_JsonPatch_does_not_deserialize() { @@ -189,7 +189,7 @@ public async Task Test_JsonPatch_does_not_deserialize() _formDataValidator.Setup(fdv => fdv.ValidateFormData( It.Is(i => i == _instance), It.Is(de => de == _dataElement), - It.IsAny(), + It.IsAny(), null)) .ReturnsAsync(validationIssues); diff --git a/test/Altinn.App.Core.Tests/Internal/Pdf/PdfServiceTests.cs b/test/Altinn.App.Core.Tests/Internal/Pdf/PdfServiceTests.cs index f979ad585..948fab4cd 100644 --- a/test/Altinn.App.Core.Tests/Internal/Pdf/PdfServiceTests.cs +++ b/test/Altinn.App.Core.Tests/Internal/Pdf/PdfServiceTests.cs @@ -152,7 +152,7 @@ public async Task GenerateAndStorePdf_with_generatedFrom() var dataModelId = Guid.NewGuid(); var attachmentId = Guid.NewGuid(); - + Instance instance = new() { Id = $"509378/{Guid.NewGuid()}", diff --git a/test/Altinn.App.Core.Tests/Internal/Process/Action/TestData/UserActionAuthorizerStub.cs b/test/Altinn.App.Core.Tests/Internal/Process/Action/TestData/UserActionAuthorizerStub.cs index 036642024..62bb2f6e2 100644 --- a/test/Altinn.App.Core.Tests/Internal/Process/Action/TestData/UserActionAuthorizerStub.cs +++ b/test/Altinn.App.Core.Tests/Internal/Process/Action/TestData/UserActionAuthorizerStub.cs @@ -4,7 +4,7 @@ namespace Altinn.App.Core.Tests.Internal.Process.Action.TestData { - public class UserActionAuthorizerStub: IUserActionAuthorizer + public class UserActionAuthorizerStub : IUserActionAuthorizer { public Task AuthorizeAction(UserActionAuthorizerContext context) { diff --git a/test/Altinn.App.Core.Tests/Internal/Process/Action/UserActionAuthorizerServiceCollectionExtensionTests.cs b/test/Altinn.App.Core.Tests/Internal/Process/Action/UserActionAuthorizerServiceCollectionExtensionTests.cs index 91b65cdb8..33bb34d72 100644 --- a/test/Altinn.App.Core.Tests/Internal/Process/Action/UserActionAuthorizerServiceCollectionExtensionTests.cs +++ b/test/Altinn.App.Core.Tests/Internal/Process/Action/UserActionAuthorizerServiceCollectionExtensionTests.cs @@ -104,7 +104,7 @@ public void AddTransientUserActionAuthorizerForAllActionsInTask_adds_IUserActinA provider.Action.Should().BeNull(); provider.Authorizer.Should().BeOfType(); } - + [Fact] public void AddTransientUserActionAuthorizerForAllActionsInAllTasks_adds_IUserActinAuthorizerProvider_without_task_and_action_set() { diff --git a/test/Altinn.App.Core.Tests/Internal/Process/Elements/AppProcessStateTests.cs b/test/Altinn.App.Core.Tests/Internal/Process/Elements/AppProcessStateTests.cs index 0ecc8c50d..1850487fe 100644 --- a/test/Altinn.App.Core.Tests/Internal/Process/Elements/AppProcessStateTests.cs +++ b/test/Altinn.App.Core.Tests/Internal/Process/Elements/AppProcessStateTests.cs @@ -61,7 +61,7 @@ public void Constructor_with_ProcessState_copies_values() AppProcessState actual = new(input); actual.Should().BeEquivalentTo(expected); } - + [Fact] public void Constructor_with_ProcessState_copies_values_validated_null() { @@ -107,7 +107,7 @@ public void Constructor_with_ProcessState_copies_values_validated_null() AppProcessState actual = new(input); actual.Should().BeEquivalentTo(expected); } - + [Fact] public void Constructor_with_ProcessState_copies_values_currenttask_null() { diff --git a/test/Altinn.App.Core.Tests/Internal/Process/ExpressionsExclusiveGatewayTests.cs b/test/Altinn.App.Core.Tests/Internal/Process/ExpressionsExclusiveGatewayTests.cs index 5d02a4be4..f0e407c75 100644 --- a/test/Altinn.App.Core.Tests/Internal/Process/ExpressionsExclusiveGatewayTests.cs +++ b/test/Altinn.App.Core.Tests/Internal/Process/ExpressionsExclusiveGatewayTests.cs @@ -244,7 +244,7 @@ public async Task FilterAsync_Expression_filters_based_on_datamodel_set_by_layou Assert.Single(result); Assert.Equal("2", result[0].Id); } - + [Fact] public async Task FilterAsync_Expression_filters_based_on_datamodel_set_by_gateway() { @@ -336,7 +336,7 @@ public async Task FilterAsync_Expression_filters_based_on_datamodel_set_by_gatew Assert.Single(result); Assert.Equal("2", result[0].Id); } - + private static ExpressionsExclusiveGateway SetupExpressionsGateway(List dataTypes, string? layoutSets = null, object? formData = null, Type? dataType = null) { var resources = new Mock(); diff --git a/test/Altinn.App.Core.Tests/Internal/Process/ProcessEngineMetricsDecoratorTests.cs b/test/Altinn.App.Core.Tests/Internal/Process/ProcessEngineMetricsDecoratorTests.cs index 463f62d03..00af473d0 100644 --- a/test/Altinn.App.Core.Tests/Internal/Process/ProcessEngineMetricsDecoratorTests.cs +++ b/test/Altinn.App.Core.Tests/Internal/Process/ProcessEngineMetricsDecoratorTests.cs @@ -26,13 +26,13 @@ public async Task StartProcess_calls_decorated_service_and_increments_success_co var decorator = new ProcessEngineMetricsDecorator(processEngine.Object); (await ReadPrometheusMetricsToString()).Should().NotContain("altinn_app_process_start_count{result=\"success\"}"); - var result = decorator.StartProcess(new ProcessStartRequest()); + var result = await decorator.StartProcess(new ProcessStartRequest()); (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_start_count{result=\"success\"} 1"); - result.Result.Success.Should().BeTrue(); - result = decorator.StartProcess(new ProcessStartRequest()); + result.Success.Should().BeTrue(); + result = await decorator.StartProcess(new ProcessStartRequest()); (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_start_count{result=\"success\"} 2"); - result.Result.Success.Should().BeTrue(); + result.Success.Should().BeTrue(); processEngine.Verify(p => p.StartProcess(It.IsAny()), Times.Exactly(2)); processEngine.VerifyNoOtherCalls(); } @@ -46,13 +46,13 @@ public async Task StartProcess_calls_decorated_service_and_increments_failure_co var decorator = new ProcessEngineMetricsDecorator(processEngine.Object); (await ReadPrometheusMetricsToString()).Should().NotContain("altinn_app_process_start_count{result=\"failure\"}"); - var result = decorator.StartProcess(new ProcessStartRequest()); + var result = await decorator.StartProcess(new ProcessStartRequest()); (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_start_count{result=\"failure\"} 1"); - result.Result.Success.Should().BeFalse(); - result = decorator.StartProcess(new ProcessStartRequest()); + result.Success.Should().BeFalse(); + result = await decorator.StartProcess(new ProcessStartRequest()); (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_start_count{result=\"failure\"} 2"); - result.Result.Success.Should().BeFalse(); + result.Success.Should().BeFalse(); processEngine.Verify(p => p.StartProcess(It.IsAny()), Times.Exactly(2)); processEngine.VerifyNoOtherCalls(); } @@ -66,7 +66,7 @@ public async Task Next_calls_decorated_service_and_increments_success_counter_wh var decorator = new ProcessEngineMetricsDecorator(processEngine.Object); (await ReadPrometheusMetricsToString()).Should().NotContain("altinn_app_process_task_next_count{result=\"success\",action=\"write\",task=\"Task_1\"}"); - var result = decorator.Next(new ProcessNextRequest() + var result = await decorator.Next(new ProcessNextRequest() { Instance = new() { @@ -82,8 +82,8 @@ public async Task Next_calls_decorated_service_and_increments_success_counter_wh }); (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_task_next_count{result=\"success\",action=\"write\",task=\"Task_1\"} 1"); - result.Result.Success.Should().BeTrue(); - result = decorator.Next(new ProcessNextRequest() + result.Success.Should().BeTrue(); + result = await decorator.Next(new ProcessNextRequest() { Instance = new() { @@ -99,7 +99,7 @@ public async Task Next_calls_decorated_service_and_increments_success_counter_wh }); var prometheusMetricsToString = await ReadPrometheusMetricsToString(); prometheusMetricsToString.Should().Contain("altinn_app_process_task_next_count{result=\"success\",action=\"write\",task=\"Task_1\"} 2"); - result.Result.Success.Should().BeTrue(); + result.Success.Should().BeTrue(); processEngine.Verify(p => p.Next(It.IsAny()), Times.Exactly(2)); processEngine.VerifyNoOtherCalls(); } @@ -113,7 +113,7 @@ public async Task Next_calls_decorated_service_and_increments_failure_counter_wh var decorator = new ProcessEngineMetricsDecorator(processEngine.Object); (await ReadPrometheusMetricsToString()).Should().NotContain("altinn_app_process_task_next_count{result=\"failure\",action=\"write\",task=\"Task_1\"}"); - var result = decorator.Next(new ProcessNextRequest() + var result = await decorator.Next(new ProcessNextRequest() { Instance = new() { @@ -129,8 +129,8 @@ public async Task Next_calls_decorated_service_and_increments_failure_counter_wh }); (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_task_next_count{result=\"failure\",action=\"write\",task=\"Task_1\"} 1"); - result.Result.Success.Should().BeFalse(); - result = decorator.Next(new ProcessNextRequest() + result.Success.Should().BeFalse(); + result = await decorator.Next(new ProcessNextRequest() { Instance = new() { @@ -146,7 +146,7 @@ public async Task Next_calls_decorated_service_and_increments_failure_counter_wh }); var prometheusMetricsToString = await ReadPrometheusMetricsToString(); prometheusMetricsToString.Should().Contain("altinn_app_process_task_next_count{result=\"failure\",action=\"write\",task=\"Task_1\"} 2"); - result.Result.Success.Should().BeFalse(); + result.Success.Should().BeFalse(); processEngine.Verify(p => p.Next(It.IsAny()), Times.Exactly(2)); processEngine.VerifyNoOtherCalls(); } @@ -175,7 +175,7 @@ public async Task Next_calls_decorated_service_and_increments_success_and_end_co (await ReadPrometheusMetricsToString()).Should().NotContain("altinn_app_process_end_count{result=\"success\"}"); (await ReadPrometheusMetricsToString()).Should().NotContain("altinn_app_process_end_time_total{result=\"success\"}"); - var result = decorator.Next(new ProcessNextRequest() + var result = await decorator.Next(new ProcessNextRequest() { Instance = new() { @@ -193,8 +193,8 @@ public async Task Next_calls_decorated_service_and_increments_success_and_end_co (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_task_next_count{result=\"success\",action=\"confirm\",task=\"Task_2\"} 1"); (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_end_count{result=\"success\"} 1"); (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_end_time_total{result=\"success\"} 20"); - result.Result.Success.Should().BeTrue(); - result = decorator.Next(new ProcessNextRequest() + result.Success.Should().BeTrue(); + result = await decorator.Next(new ProcessNextRequest() { Instance = new() { @@ -212,7 +212,7 @@ public async Task Next_calls_decorated_service_and_increments_success_and_end_co prometheusMetricsToString.Should().Contain("altinn_app_process_task_next_count{result=\"success\",action=\"confirm\",task=\"Task_2\"} 2"); (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_end_count{result=\"success\"} 2"); (await ReadPrometheusMetricsToString()).Should().Contain("altinn_app_process_end_time_total{result=\"success\"} 40"); - result.Result.Success.Should().BeTrue(); + result.Success.Should().BeTrue(); processEngine.Verify(p => p.Next(It.IsAny()), Times.Exactly(2)); processEngine.VerifyNoOtherCalls(); } @@ -240,7 +240,7 @@ public async Task Next_calls_decorated_service_and_increments_failure_and_end_co prometheusMetricsToString.Should().NotContain("altinn_app_process_end_count{result=\"failure\"}"); prometheusMetricsToString.Should().NotContain("altinn_app_process_end_time_total{result=\"failure\"}"); - var result = decorator.Next(new ProcessNextRequest() + var result = await decorator.Next(new ProcessNextRequest() { Instance = new() { @@ -259,8 +259,8 @@ public async Task Next_calls_decorated_service_and_increments_failure_and_end_co prometheusMetricsToString.Should().Contain("altinn_app_process_task_next_count{result=\"failure\",action=\"confirm\",task=\"Task_3\"} 1"); prometheusMetricsToString.Should().Contain("altinn_app_process_end_count{result=\"failure\"} 1"); prometheusMetricsToString.Should().NotContain("altinn_app_process_end_time_total{result=\"failure\"}"); - result.Result.Success.Should().BeFalse(); - result = decorator.Next(new ProcessNextRequest() + result.Success.Should().BeFalse(); + result = await decorator.Next(new ProcessNextRequest() { Instance = new() { @@ -278,7 +278,7 @@ public async Task Next_calls_decorated_service_and_increments_failure_and_end_co prometheusMetricsToString.Should().Contain("altinn_app_process_task_next_count{result=\"failure\",action=\"confirm\",task=\"Task_3\"} 2"); prometheusMetricsToString.Should().Contain("altinn_app_process_end_count{result=\"failure\"} 2"); prometheusMetricsToString.Should().NotContain("altinn_app_process_end_time_total{result=\"failure\"}"); - result.Result.Success.Should().BeFalse(); + result.Success.Should().BeFalse(); processEngine.Verify(p => p.Next(It.IsAny()), Times.Exactly(2)); processEngine.VerifyNoOtherCalls(); } diff --git a/test/Altinn.App.Core.Tests/Internal/Process/ProcessEngineTest.cs b/test/Altinn.App.Core.Tests/Internal/Process/ProcessEngineTest.cs index 0d18769eb..bcbb55a1b 100644 --- a/test/Altinn.App.Core.Tests/Internal/Process/ProcessEngineTest.cs +++ b/test/Altinn.App.Core.Tests/Internal/Process/ProcessEngineTest.cs @@ -933,7 +933,7 @@ public static bool JsonCompare(object expected, object actual) { Console.WriteLine("Not equal"); } - + return jsonCompare; } } diff --git a/test/Altinn.App.Core.Tests/Internal/Process/ProcessNavigatorTests.cs b/test/Altinn.App.Core.Tests/Internal/Process/ProcessNavigatorTests.cs index a54f2e9c0..130e16ffb 100644 --- a/test/Altinn.App.Core.Tests/Internal/Process/ProcessNavigatorTests.cs +++ b/test/Altinn.App.Core.Tests/Internal/Process/ProcessNavigatorTests.cs @@ -20,20 +20,20 @@ public async void GetNextTask_returns_next_element_if_no_gateway() IProcessNavigator processNavigator = SetupProcessNavigator("simple-linear.bpmn", new List()); ProcessElement nextElements = await processNavigator.GetNextTask(new Instance(), "Task1", null); nextElements.Should().BeEquivalentTo(new ProcessTask() + { + Id = "Task2", + Name = "Bekreft skjemadata", + Incoming = new List { "Flow2" }, + Outgoing = new List { "Flow3" }, + ExtensionElements = new ExtensionElements() { - Id = "Task2", - Name = "Bekreft skjemadata", - Incoming = new List { "Flow2" }, - Outgoing = new List { "Flow3" }, - ExtensionElements = new ExtensionElements() + TaskExtension = new() { - TaskExtension = new() - { - TaskType = "confirmation", - AltinnActions = new() - }, - } - }); + TaskType = "confirmation", + AltinnActions = new() + }, + } + }); } [Fact] @@ -50,24 +50,24 @@ public async void GetNextTask_returns_default_if_no_filtering_is_implemented_and IProcessNavigator processNavigator = SetupProcessNavigator("simple-gateway-default.bpmn", new List()); ProcessElement nextElements = await processNavigator.GetNextTask(new Instance(), "Task1", null); nextElements.Should().BeEquivalentTo(new ProcessTask() + { + Id = "Task2", + Name = null!, + ExtensionElements = new() { - Id = "Task2", - Name = null!, - ExtensionElements = new() + TaskExtension = new() { - TaskExtension = new() - { - TaskType = "confirm", - AltinnActions = new() + TaskType = "confirm", + AltinnActions = new() { new("confirm"), new("reject") } - } - }, - Incoming = new List { "Flow3" }, - Outgoing = new List { "Flow5" } - }); + } + }, + Incoming = new List { "Flow3" }, + Outgoing = new List { "Flow5" } + }); } [Fact] @@ -84,28 +84,28 @@ public async void GetNextTask_runs_custom_filter_and_returns_result() { "choose", "Flow3" } } }; - + ProcessElement nextElements = await processNavigator.GetNextTask(i, "Task1", null); nextElements.Should().BeEquivalentTo(new ProcessTask() + { + Id = "Task2", + Name = null!, + ExtensionElements = new() { - Id = "Task2", - Name = null!, - ExtensionElements = new() + TaskExtension = new() { - TaskExtension = new() - { - TaskType = "data", - AltinnActions = new() + TaskType = "data", + AltinnActions = new() { new("submit") } - } - }, - Incoming = new List { "Flow3" }, - Outgoing = new List { "Flow5" } - }); + } + }, + Incoming = new List { "Flow3" }, + Outgoing = new List { "Flow5" } + }); } - + [Fact] public async void GetNextTask_throws_ProcessException_if_multiple_targets_found() { @@ -141,14 +141,14 @@ public async void GetNextTask_follows_downstream_gateways() }; ProcessElement nextElements = await processNavigator.GetNextTask(i, "Task1", null); nextElements.Should().BeEquivalentTo(new EndEvent() - { - Id = "EndEvent", - Name = null!, - Incoming = new List { "Flow6" }, - Outgoing = new List() - }); + { + Id = "EndEvent", + Name = null!, + Incoming = new List { "Flow6" }, + Outgoing = new List() + }); } - + [Fact] public async void GetNextTask_runs_custom_filter_and_returns_empty_list_if_all_filtered_out() { @@ -165,21 +165,21 @@ public async void GetNextTask_runs_custom_filter_and_returns_empty_list_if_all_f { "choose2", "Bar" } } }; - + ProcessElement nextElements = await processNavigator.GetNextTask(i, "Task1", null); nextElements.Should().BeNull(); } - + [Fact] public async void GetNextTask_returns_empty_list_if_element_has_no_next() { IProcessNavigator processNavigator = SetupProcessNavigator("simple-gateway-with-join-gateway.bpmn", new List()); Instance i = new Instance(); - + ProcessElement nextElements = await processNavigator.GetNextTask(i, "EndEvent", null); nextElements.Should().BeNull(); } - + private static IProcessNavigator SetupProcessNavigator(string bpmnfile, IEnumerable gatewayFilters) { ProcessReader pr = ProcessTestUtils.SetupProcessReader(bpmnfile); diff --git a/test/Altinn.App.Core.Tests/Internal/Process/TestUtils/ProcessTestUtils.cs b/test/Altinn.App.Core.Tests/Internal/Process/TestUtils/ProcessTestUtils.cs index 8901f78cc..fbb2a1f42 100644 --- a/test/Altinn.App.Core.Tests/Internal/Process/TestUtils/ProcessTestUtils.cs +++ b/test/Altinn.App.Core.Tests/Internal/Process/TestUtils/ProcessTestUtils.cs @@ -6,14 +6,14 @@ namespace Altinn.App.Core.Tests.Internal.Process.TestUtils; internal static class ProcessTestUtils { private static readonly string TestDataPath = Path.Combine("Internal", "Process", "TestData"); - + internal static ProcessReader SetupProcessReader(string bpmnfile, string? testDataPath = null) { if (testDataPath == null) { testDataPath = TestDataPath; } - + Mock processServiceMock = new Mock(); var s = new FileStream(Path.Combine(testDataPath, bpmnfile), FileMode.Open, FileAccess.Read); processServiceMock.Setup(p => p.GetProcessDefinition()).Returns(s); diff --git a/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/ExpressionTestCaseRoot.cs b/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/ExpressionTestCaseRoot.cs index c50f59638..82ef1d00e 100644 --- a/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/ExpressionTestCaseRoot.cs +++ b/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/ExpressionTestCaseRoot.cs @@ -53,7 +53,7 @@ public class ExpressionTestCaseRoot [JsonPropertyName("instance")] public Instance? Instance { get; set; } - + [JsonPropertyName("gatewayAction")] public string? GatewayAction { get; set; } diff --git a/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/TestBackendExclusiveFunctions.cs b/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/TestBackendExclusiveFunctions.cs index 99d2a84be..4da0f17e7 100644 --- a/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/TestBackendExclusiveFunctions.cs +++ b/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/TestBackendExclusiveFunctions.cs @@ -18,7 +18,7 @@ public TestBackendExclusiveFunctions(ITestOutputHelper output) { _output = output; } - + [Theory] [ExclusiveTest("gatewayAction")] public void GatewayAction_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); diff --git a/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/TestFunctions.cs b/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/TestFunctions.cs index 421b18b77..8cc96de4a 100644 --- a/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/TestFunctions.cs +++ b/test/Altinn.App.Core.Tests/LayoutExpressions/CommonTests/TestFunctions.cs @@ -30,7 +30,7 @@ public TestFunctions(ITestOutputHelper output) [Theory] [SharedTest("component")] public void Component_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); - + [Theory] [SharedTest("commaContains")] public void CommaContains_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); @@ -70,7 +70,7 @@ public TestFunctions(ITestOutputHelper output) [Theory] [SharedTest("not")] public void Not_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); - + [Theory] [SharedTest("notContains")] public void NotContains_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); @@ -94,27 +94,27 @@ public TestFunctions(ITestOutputHelper output) [Theory] [SharedTest("or")] public void Or_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); - + [Theory] [SharedTest("unknown")] public void Unknown_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); - + [Theory] [SharedTest("upperCase")] public void UpperCase_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); - + [Theory] [SharedTest("lowerCase")] public void LowerCase_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); - + [Theory] [SharedTest("startsWith")] public void StartsWith_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); - + [Theory] [SharedTest("stringLength")] public void StringLength_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); - + [Theory] [SharedTest("round")] public void Round_Theory(ExpressionTestCaseRoot test) => RunTestCase(test); diff --git a/test/Altinn.App.Core.Tests/LayoutExpressions/TestDataModel.cs b/test/Altinn.App.Core.Tests/LayoutExpressions/TestDataModel.cs index bc3b0a350..65200a4b2 100644 --- a/test/Altinn.App.Core.Tests/LayoutExpressions/TestDataModel.cs +++ b/test/Altinn.App.Core.Tests/LayoutExpressions/TestDataModel.cs @@ -434,7 +434,6 @@ public void TestAddIndicies() // First index is ignored if it is explicit modelHelper.AddIndicies("friends[0].friends", new int[] { 2, 3 }).Should().Be("friends[0].friends[3]"); - } [Fact] diff --git a/test/Altinn.App.Core.Tests/Models/AppIdentifierTests.cs b/test/Altinn.App.Core.Tests/Models/AppIdentifierTests.cs index 86ba07149..7933e4487 100644 --- a/test/Altinn.App.Core.Tests/Models/AppIdentifierTests.cs +++ b/test/Altinn.App.Core.Tests/Models/AppIdentifierTests.cs @@ -15,7 +15,7 @@ public void Constructor_AppId_ShouldReturnValidInstance() var org = "ttd"; var app = "test-app"; var appId = $"{org}/{app}"; - + var appIdentifier = new AppIdentifier(appId); appIdentifier.Org.Should().Be(org); @@ -108,5 +108,5 @@ public void CreateFromUrl_Null_ShouldThrowArgumentNullException() } } - #pragma warning restore CA1806 // Do not ignore method results +#pragma warning restore CA1806 // Do not ignore method results } diff --git a/test/Altinn.App.Core.Tests/Models/ApplicationMetdataTests.cs b/test/Altinn.App.Core.Tests/Models/ApplicationMetdataTests.cs index 44068cc13..041833f24 100644 --- a/test/Altinn.App.Core.Tests/Models/ApplicationMetdataTests.cs +++ b/test/Altinn.App.Core.Tests/Models/ApplicationMetdataTests.cs @@ -15,7 +15,7 @@ public void ConstructorSetIdAndAppIdentifier() AppIdentifier expected = new AppIdentifier("ttd/test"); metadata.AppIdentifier.Should().BeEquivalentTo(expected); } - + [Fact] public void UpdatingIdUpdatesAppIdentifier() { @@ -28,7 +28,7 @@ public void UpdatingIdUpdatesAppIdentifier() AppIdentifier expectedUpdate = new AppIdentifier("ttd/updated"); metadata.AppIdentifier.Should().BeEquivalentTo(expectedUpdate); } - + [Fact] public void UpdatingIdFailsIfInvalidApplicationIdFormat() { diff --git a/test/Altinn.App.Core.Tests/Models/InstanceIdentifierTests.cs b/test/Altinn.App.Core.Tests/Models/InstanceIdentifierTests.cs index c75d741de..596ef4304 100644 --- a/test/Altinn.App.Core.Tests/Models/InstanceIdentifierTests.cs +++ b/test/Altinn.App.Core.Tests/Models/InstanceIdentifierTests.cs @@ -25,7 +25,7 @@ public void Url_CreateFromUrl_ShouldReturnOwnerIdAndInstaceGuid(string url, int public void Url_CreateFromUrl_ShouldThrowExceptionOnInvalidUrl() { var url = "/yabbin/hvem-er-hvem/512345/2539cacc-1f49-4852-907b-d184e7285a60/process/next"; - + Action action = () => InstanceIdentifier.CreateFromUrl(url); action.Should().Throw(); diff --git a/test/Altinn.App.Core.Tests/Models/MimeTypeTests.cs b/test/Altinn.App.Core.Tests/Models/MimeTypeTests.cs index a7cfe2aa9..bddf02c7d 100644 --- a/test/Altinn.App.Core.Tests/Models/MimeTypeTests.cs +++ b/test/Altinn.App.Core.Tests/Models/MimeTypeTests.cs @@ -14,42 +14,42 @@ public void Equals_matches_string_to_type() var mimeType = new MimeType("application/pdf"); mimeType.Equals("application/pdf").Should().BeTrue(); } - + [Fact] public void Equals_not_matches_string_to_type_no_aliases() { var mimeType = new MimeType("application/pdf"); mimeType.Equals("application/zip").Should().BeFalse(); } - + [Fact] public void Equals_matches_string_to_alias() { var mimeType = new MimeType("application/zip", "application/x-zip-compressed"); mimeType.Equals("application/x-zip-compressed").Should().BeTrue(); } - + [Fact] public void Equals_matches_stringvalues_to_type() { var mimeType = new MimeType("application/zip", "application/x-zip-compressed"); mimeType.Equals(new StringValues("application/zip")).Should().BeTrue(); } - + [Fact] public void Equals_matches_mimetype_when_type_and_alias_equal() { var mimeType = new MimeType("application/zip", "application/x-zip-compressed"); mimeType.Equals(new MimeType("application/zip", "application/x-zip-compressed")).Should().BeTrue(); } - + [Fact] public void Equals_not_matches_mimetype_when_type_not_equal() { var mimeType = new MimeType("application/zip", "application/x-zip-compressed"); mimeType.Equals(new MimeType("application/x-zip-compressed", "application/x-zip-compressed")).Should().BeFalse(); } - + [Fact] public void Equals_not_matches_mimetype_when_alias_not_equal() { @@ -63,7 +63,7 @@ public void Equals_returns_false_when_object_is_null() var mimeType = new MimeType("application/zip", "application/x-zip-compressed"); mimeType.Equals(null).Should().BeFalse(); } - + [Fact] public void Equals_returns_false_when_unknown_object() { diff --git a/test/Altinn.App.Core.Tests/Models/PageComponentConverterTests.cs b/test/Altinn.App.Core.Tests/Models/PageComponentConverterTests.cs index 66aa63607..c9f90d7a3 100644 --- a/test/Altinn.App.Core.Tests/Models/PageComponentConverterTests.cs +++ b/test/Altinn.App.Core.Tests/Models/PageComponentConverterTests.cs @@ -73,7 +73,6 @@ public class PageComponentConverterTestModel public JsonElement Layout { get; set; } public HierarchyTestModel[]? ExpectedHierarchy { get; set; } - } public class HierarchyTestModel diff --git a/test/Altinn.App.Core.Tests/Models/Result/ServiceResultTests.cs b/test/Altinn.App.Core.Tests/Models/Result/ServiceResultTests.cs index cb00b1787..772827933 100644 --- a/test/Altinn.App.Core.Tests/Models/Result/ServiceResultTests.cs +++ b/test/Altinn.App.Core.Tests/Models/Result/ServiceResultTests.cs @@ -15,7 +15,7 @@ public void Ok_result() res.Ok.Should().Be(value); res.Error.Should().BeNull(); } - + [Fact] public void Ok_result_handles_null() { @@ -25,7 +25,7 @@ public void Ok_result_handles_null() res.Ok.Should().BeNull(); res.Error.Should().BeNull(); } - + [Fact] public void Error_result() { diff --git a/test/Altinn.App.Core.Tests/Options/Altinn2Provider/Altinn2OptionsTests.cs b/test/Altinn.App.Core.Tests/Options/Altinn2Provider/Altinn2OptionsTests.cs index b1ab78a22..f3d2b0e3b 100644 --- a/test/Altinn.App.Core.Tests/Options/Altinn2Provider/Altinn2OptionsTests.cs +++ b/test/Altinn.App.Core.Tests/Options/Altinn2Provider/Altinn2OptionsTests.cs @@ -141,7 +141,7 @@ public async Task Altinn2OptionsTests_NoCodeListVersionProvided() public void Altinn2OptionsTests_Altinn2MetadataClientNotRegistered() { var services = new ServiceCollection(); - + services.AddAltinn2CodeList( id: "OnlyNorway", transform: (code) => new() { Value = code.Code, Label = code.Value1 }, diff --git a/test/Altinn.App.Core.Tests/Options/AppOptionsFactoryTests.cs b/test/Altinn.App.Core.Tests/Options/AppOptionsFactoryTests.cs index 39a610ecd..11e609607 100644 --- a/test/Altinn.App.Core.Tests/Options/AppOptionsFactoryTests.cs +++ b/test/Altinn.App.Core.Tests/Options/AppOptionsFactoryTests.cs @@ -30,7 +30,7 @@ public void GetOptionsProvider_NoCustomOptionsProvider_ShouldReturnDefaultTwice( IAppOptionsProvider optionsProvider1 = factory.GetOptionsProvider("fylke"); IAppOptionsProvider optionsProvider2 = factory.GetOptionsProvider("kommune"); - + optionsProvider1.Id.Should().Be("fylke"); optionsProvider2.Id.Should().Be("kommune"); } diff --git a/test/Altinn.App.Core.Tests/Options/NullInstanceAppOptionsProviderTests.cs b/test/Altinn.App.Core.Tests/Options/NullInstanceAppOptionsProviderTests.cs index 176ca781d..409b90991 100644 --- a/test/Altinn.App.Core.Tests/Options/NullInstanceAppOptionsProviderTests.cs +++ b/test/Altinn.App.Core.Tests/Options/NullInstanceAppOptionsProviderTests.cs @@ -9,12 +9,13 @@ namespace Altinn.App.PlatformServices.Tests.Options public class NullInstanceAppOptionsProviderTests { [Fact] - public void Constructor_InitializedWithEmptyValues() + public async void Constructor_InitializedWithEmptyValues() { var provider = new NullInstanceAppOptionsProvider(); provider.Id.Should().Be(string.Empty); - provider.GetInstanceAppOptionsAsync(new InstanceIdentifier(12345, Guid.NewGuid()), "nb", new Dictionary()).Result.Options.Should().BeNull(); + var options = await provider.GetInstanceAppOptionsAsync(new InstanceIdentifier(12345, Guid.NewGuid()), "nb", new Dictionary()); + options.Options.Should().BeNull(); } } }