From 8fce9d59275b6b8cda1ff621a9ce5effd15c15b9 Mon Sep 17 00:00:00 2001 From: Daniel Almeida <115644988+daniel-almeida-konkconsulting@users.noreply.github.com> Date: Mon, 2 Sep 2024 09:01:53 +0100 Subject: [PATCH] Delete unnecessary handler tests (#795) * chore: remove challenges module unnecessary handler tests * refactor: remove unnecessary unit tests for handlers * test: integration tests for missing test cases * refactor: remove redundant handler tests * chore: add comment for missing integration tests * refactor: remove redundant handler tests * chore: add comments for missing integration tests * test: Add metric statuses update unit test * test: add integration tests for missing scenarios * fix: add missing byte array converter * fix: use valid identity address, albeit a non existent one, to avoid 400 error before 404 * refactor: minor changes after code review --------- Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com> --- .../Features/Clients/PUT.feature | 2 +- .../Identities/{identityAddress}/GET.feature | 15 ++ .../Features/IndividualQuotas/DELETE.feature | 6 + .../Features/IndividualQuotas/POST.feature | 6 + .../Features/TierQuotas/DELETE.feature | 6 + .../Features/TierQuotas/POST.feature | 6 + .../Features/Tiers/{id}/GET.feature | 15 ++ .../IdentitiesApiStepDefinitions.cs | 6 +- .../IndividualQuotaStepDefinitions.cs | 17 ++ .../TierQuotaStepDefinitions.cs | 17 ++ .../StepDefinitions/TiersStepDefinitions.cs | 39 +++- .../Self/DeletionProcess/PUT.feature | 10 ++ .../Features/Relationships/POST.feature | 2 +- .../IdentitiesApiStepDefinitions.cs | 21 ++- .../HandlerTests.cs | 32 ---- .../ChangeClientSecret/HandlerTests.cs | 41 ----- .../Commands/UpdateClient/HandlerTests.cs | 166 ------------------ .../Commands/DeleteDevice/HandlerTests.cs | 111 ------------ .../UpdateActiveDevice/HandlerTests.cs | 79 --------- ...ProcessAuditLogsByAddressStubRepository.cs | 88 ---------- .../FindByAddressStubRepository.cs | 83 --------- .../Queries/GetIdentity/HandlerTests.cs | 58 ------ .../ListIdentities/FindAllStubRepository.cs | 83 --------- .../Queries/ListIdentities/HandlerTests.cs | 81 --------- .../Tiers/Commands/CreateTier/HandlerTests.cs | 60 ------- .../ListTiers/FindAllStubRepository.cs | 71 -------- .../Tiers/Queries/ListTiers/HandlerTests.cs | 82 --------- .../ListQuotasForIdentity/HandlerTests.cs | 70 -------- .../Queries/GetIdentity/HandlerTests.cs | 88 ---------- .../CreateQuotaForIdentity/HandlerTests.cs | 81 +-------- .../Quotas/CreateQuotaForTier/HandlerTests.cs | 63 ------- .../DeleteIndividualQuota/HandlerTests.cs | 109 ------------ .../DeleteTierQuotaDefinition/HandlerTests.cs | 128 -------------- .../Tests/Tiers/GetTierById/HandlerTests.cs | 93 ---------- .../AcceptRelationship/Handler.Tests.cs | 81 --------- .../Handler.Tests.cs | 83 --------- .../CreateRelationship/Handler.Tests.cs | 150 ---------------- .../DecomposeRelationship/Handler.Tests.cs | 82 --------- .../RejectRelationship/Handler.Tests.cs | 81 --------- .../Handler.Tests.cs | 84 --------- .../Handler.Tests.cs | 80 --------- .../RevokeRelationship/Handler.Tests.cs | 81 --------- .../Handler.Tests.cs | 77 -------- .../TerminateRelationship/Handler.Tests.cs | 83 --------- Sdks/AdminApi.Sdk/src/Client.cs | 2 + 45 files changed, 163 insertions(+), 2556 deletions(-) create mode 100644 Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Identities/{identityAddress}/GET.feature create mode 100644 Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Tiers/{id}/GET.feature create mode 100644 Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/Features/Identities/Self/DeletionProcess/PUT.feature delete mode 100644 Modules/Challenges/test/Challenges.Application.Tests/Tests/Identities/Commands/DeleteIdentityCommandTests/HandlerTests.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Clients/Commands/ChangeClientSecret/HandlerTests.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Clients/Commands/UpdateClient/HandlerTests.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Devices/Commands/DeleteDevice/HandlerTests.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Devices/Commands/UpdateActiveDevice/HandlerTests.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetDeletionProcessesAuditLogs/FindDeletionProcessAuditLogsByAddressStubRepository.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetIdentity/FindByAddressStubRepository.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetIdentity/HandlerTests.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/ListIdentities/FindAllStubRepository.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/ListIdentities/HandlerTests.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Commands/CreateTier/HandlerTests.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Queries/ListTiers/FindAllStubRepository.cs delete mode 100644 Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Queries/ListTiers/HandlerTests.cs delete mode 100644 Modules/Quotas/test/Quotas.Application.Tests/Tests/Identities/ListQuotasForIdentity/HandlerTests.cs delete mode 100644 Modules/Quotas/test/Quotas.Application.Tests/Tests/Identities/Queries/GetIdentity/HandlerTests.cs delete mode 100644 Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForTier/HandlerTests.cs delete mode 100644 Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteIndividualQuota/HandlerTests.cs delete mode 100644 Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteTierQuotaDefinition/HandlerTests.cs delete mode 100644 Modules/Quotas/test/Quotas.Application.Tests/Tests/Tiers/GetTierById/HandlerTests.cs delete mode 100644 Modules/Relationships/src/Relationships.Application/Relationships/Commands/AcceptRelationship/Handler.Tests.cs delete mode 100644 Modules/Relationships/src/Relationships.Application/Relationships/Commands/AcceptRelationshipReactivation/Handler.Tests.cs delete mode 100644 Modules/Relationships/src/Relationships.Application/Relationships/Commands/CreateRelationship/Handler.Tests.cs delete mode 100644 Modules/Relationships/src/Relationships.Application/Relationships/Commands/DecomposeRelationship/Handler.Tests.cs delete mode 100644 Modules/Relationships/src/Relationships.Application/Relationships/Commands/RejectRelationship/Handler.Tests.cs delete mode 100644 Modules/Relationships/src/Relationships.Application/Relationships/Commands/RejectRelationshipReactivation/Handler.Tests.cs delete mode 100644 Modules/Relationships/src/Relationships.Application/Relationships/Commands/RequestRelationshipReactivation/Handler.Tests.cs delete mode 100644 Modules/Relationships/src/Relationships.Application/Relationships/Commands/RevokeRelationship/Handler.Tests.cs delete mode 100644 Modules/Relationships/src/Relationships.Application/Relationships/Commands/RevokeRelationshipReactivation/Handler.Tests.cs delete mode 100644 Modules/Relationships/src/Relationships.Application/Relationships/Commands/TerminateRelationship/Handler.Tests.cs diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Clients/PUT.feature b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Clients/PUT.feature index 3be484eca6..d4703ec796 100644 --- a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Clients/PUT.feature +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Clients/PUT.feature @@ -23,7 +23,7 @@ Scenario: Changing the default tier of an existing Client with a non-existent ti Then the response status code is 400 (Bad request) And the response content contains an error with the error code "error.platform.validation.device.tierIdInvalidOrDoesNotExist" -Scenario: Changing the default tier of a non-existing Client +Scenario: Updating a non-existing Client When a PUT request is sent to the /Clients/{c.clientId} endpoint with a non-existing clientId Then the response status code is 404 (Not Found) And the response content contains an error with the error code "error.platform.recordNotFound" diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Identities/{identityAddress}/GET.feature b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Identities/{identityAddress}/GET.feature new file mode 100644 index 0000000000..44f444b73d --- /dev/null +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Identities/{identityAddress}/GET.feature @@ -0,0 +1,15 @@ +@Integration +Feature: GET Identities/{identityAddress} + +User requests an Identity + +Scenario: Requesting an Identity by address + Given an Identity i + When a GET request is sent to the /Identities/{i.address} endpoint + Then the response status code is 200 (OK) + And the response contains Identity i + +Scenario: Requesting an Identity with non existent address + When a GET request is sent to the /Identities/{address} endpoint with an inexistent address + Then the response status code is 404 (Not Found) + And the response content contains an error with the error code "error.platform.recordNotFound" diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/IndividualQuotas/DELETE.feature b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/IndividualQuotas/DELETE.feature index ba11d4510f..1e5e0430b6 100644 --- a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/IndividualQuotas/DELETE.feature +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/IndividualQuotas/DELETE.feature @@ -13,3 +13,9 @@ Scenario: Deleting an inexistent Individual Quota When a DELETE request is sent to the /Identities/{i.address}/Quotas/inexistentQuotaId endpoint Then the response status code is 404 (Not Found) And the response content contains an error with the error code "error.platform.recordNotFound" + +Scenario: Deleting an Individual Quota for a non existent Identity + Given an Identity i with an IndividualQuota q + When a DELETE request is sent to the /Identities/{nonExistentAddress}/Quotas/{q.id} endpoint + Then the response status code is 404 (Not Found) + And the response content contains an error with the error code "error.platform.recordNotFound" diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/IndividualQuotas/POST.feature b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/IndividualQuotas/POST.feature index cf06f96531..dfba3dccc7 100644 --- a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/IndividualQuotas/POST.feature +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/IndividualQuotas/POST.feature @@ -13,3 +13,9 @@ Scenario: Creating an Individual Quota for inexistent Identity When a POST request is sent to the /Identity/{address}/Quotas endpoint with an inexistent identity address Then the response status code is 404 (Not Found) And the response content contains an error with the error code "error.platform.recordNotFound" + +Scenario: Creating an Individual Quota for a non existent Metric Key + Given an Identity i + When a POST request is sent to the /Identity/{i.id}/Quotas endpoint with an invalid metric key + Then the response status code is 400 (Bad Request) + And the response content contains an error with the error code "error.platform.quotas.unsupportedMetricKey" diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/TierQuotas/DELETE.feature b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/TierQuotas/DELETE.feature index 47162184f0..5ec67e9a9d 100644 --- a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/TierQuotas/DELETE.feature +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/TierQuotas/DELETE.feature @@ -13,3 +13,9 @@ Scenario: Deleting an inexistent Tier Quota When a DELETE request is sent to the /Tiers/{t.id}/Quotas/{quotaId} endpoint with an inexistent quota id Then the response status code is 404 (Not Found) And the response content contains an error with the error code "error.platform.recordNotFound" + +Scenario: Deleting a Tier Quota for a non existent Tier + Given a Tier t with a Quota q + When a DELETE request is sent to the /Tiers/{nonExistentTier}/Quotas/{q.id} + Then the response status code is 404 (Not Found) + And the response content contains an error with the error code "error.platform.recordNotFound" diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/TierQuotas/POST.feature b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/TierQuotas/POST.feature index 5a7d2b391c..288f753282 100644 --- a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/TierQuotas/POST.feature +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/TierQuotas/POST.feature @@ -13,3 +13,9 @@ Scenario: Creating a Tier Quota for inexistent Tier When a POST request is sent to the /Tiers/{tierId}/Quotas endpoint with an inexistent tier id Then the response status code is 404 (Not Found) And the response content contains an error with the error code "error.platform.recordNotFound" + +Scenario: Creating a Tier Quota for a non existent Metric Key + Given a Tier t + When a POST request is sent to the /Tiers/{t.id}/Quotas endpoint with an invalid metric key + Then the response status code is 400 (Bad Request) + And the response content contains an error with the error code "error.platform.quotas.unsupportedMetricKey" diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Tiers/{id}/GET.feature b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Tiers/{id}/GET.feature new file mode 100644 index 0000000000..dfa9cebd92 --- /dev/null +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/Features/Tiers/{id}/GET.feature @@ -0,0 +1,15 @@ +@Integration +Feature: GET Tiers/{id} + +User requests a Tier + +Scenario: Requesting a Tier by id + Given a Tier t + When a GET request is sent to the /Tiers/{t.id} endpoint + Then the response status code is 200 (OK) + And the response contains Tier t + +Scenario: Requesting a Tier with non existent address + When a GET request is sent to the /Tiers/{nonExistentTierId} endpoint + Then the response status code is 404 (Not Found) + And the response content contains an error with the error code "error.platform.recordNotFound" diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/IdentitiesApiStepDefinitions.cs b/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/IdentitiesApiStepDefinitions.cs index e26440d2cc..0d6290e198 100644 --- a/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/IdentitiesApiStepDefinitions.cs +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/IdentitiesApiStepDefinitions.cs @@ -3,6 +3,7 @@ using Backbone.AdminApi.Tests.Integration.Configuration; using Backbone.AdminApi.Tests.Integration.Extensions; using Backbone.BuildingBlocks.SDK.Endpoints.Common.Types; +using Backbone.UnitTestTools.Data; using Microsoft.Extensions.Options; namespace Backbone.AdminApi.Tests.Integration.StepDefinitions; @@ -10,6 +11,7 @@ namespace Backbone.AdminApi.Tests.Integration.StepDefinitions; [Binding] [Scope(Feature = "GET Identities")] [Scope(Feature = "POST Identities/{id}/DeletionProcess")] +[Scope(Feature = "GET Identities/{identityAddress}")] [Scope(Feature = "GET Identities/{identityAddress}/DeletionProcesses/AuditLogs")] internal class IdentitiesApiStepDefinitions : BaseStepDefinitions { @@ -67,7 +69,7 @@ public async Task WhenAGETRequestIsSentToTheIdentitiesAddressEndpoint() [When("a GET request is sent to the /Identities/{address} endpoint with an inexistent address")] public async Task WhenAGETRequestIsSentToTheIdentitiesAddressEndpointForAnInexistentIdentity() { - _identityResponse = await _client.Identities.GetIdentity("inexistentIdentityAddress"); + _identityResponse = await _client.Identities.GetIdentity(TestDataGenerator.CreateRandomIdentityAddress()); } [Then("the response contains a list of Identities")] @@ -123,7 +125,7 @@ public void ThenTheResponseContentIncludesAnErrorWithTheErrorCode(string errorCo { if (_identityResponse != null) { - _identityResponse!.Result!.Should().NotBeNull(); + _identityResponse!.Error!.Should().NotBeNull(); _identityResponse.Error!.Code.Should().Be(errorCode); } diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/IndividualQuotaStepDefinitions.cs b/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/IndividualQuotaStepDefinitions.cs index 2926791b29..d37adbd7d0 100644 --- a/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/IndividualQuotaStepDefinitions.cs +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/IndividualQuotaStepDefinitions.cs @@ -58,6 +58,12 @@ public async Task WhenADeleteRequestIsSentToTheDeleteIndividualQuotaEndpointWith _deleteResponse = await _client.Identities.DeleteIndividualQuota(_identityAddress, "QUOInexistentIdxxxxx"); } + [When("a DELETE request is sent to the /Identities/{nonExistentAddress}/Quotas/{q.id} endpoint")] + public async Task WhenADeleteRequestIsSentToTheDeleteIndividualQuotaEndpointWithANonExistentIdentityAddress() + { + _deleteResponse = await _client.Identities.DeleteIndividualQuota("someNonExistentIdentityAddress", _quotaId); + } + [When("a POST request is sent to the /Identity/{i.id}/Quotas endpoint")] public async Task WhenAPOSTRequestIsSentToTheCreateIndividualQuotaEndpoint() { @@ -80,6 +86,17 @@ public async Task WhenAPOSTRequestIsSentToTheCreateIndividualQuotaEndpointWithAn }); } + [When("a POST request is sent to the /Identity/{i.id}/Quotas endpoint with an invalid metric key")] + public async Task WhenAPOSTRequestIsSentToTheCreateIndividualQuotaEndpointWithAnInvalidMetricKey() + { + _createQuotaResponse = await _client.Identities.CreateIndividualQuota(_identityAddress, new CreateQuotaForIdentityRequest + { + MetricKey = "someInvalidMetricKey", + Max = 2, + Period = "Week" + }); + } + [Then(@"the response status code is (\d+) \(.+\)")] public void ThenTheResponseStatusCodeIs(int expectedStatusCode) { diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/TierQuotaStepDefinitions.cs b/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/TierQuotaStepDefinitions.cs index 8d25cc09c3..6163279918 100644 --- a/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/TierQuotaStepDefinitions.cs +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/TierQuotaStepDefinitions.cs @@ -66,6 +66,17 @@ public async Task WhenAPOSTRequestIsSentToTheCreateTierQuotaEndpoint() }); } + [When("a POST request is sent to the /Tiers/{t.id}/Quotas endpoint with an invalid metric key")] + public async Task WhenAPOSTRequestIsSentToTheCreateTierQuotaEndpointWithAnInvalidMetricKey() + { + _createTierQuotaResponse = await _client.Tiers.AddTierQuota(_tierId, new CreateQuotaForTierRequest + { + MetricKey = "SomeInvalidMetricKey", + Max = 2, + Period = "Week" + }); + } + [When("a POST request is sent to the /Tiers/{tierId}/Quotas endpoint with an inexistent tier id")] public async Task WhenAPOSTRequestIsSentToTheCreateTierQuotaEndpointForAnInexistentTier() { @@ -89,6 +100,12 @@ public async Task WhenADeleteRequestIsSentToTheDeleteTierQuotaEndpointForAnInexi _deleteResponse = await _client.Tiers.DeleteTierQuota(_tierId, "inexistentQuotaId"); } + [When("a DELETE request is sent to the /Tiers/{nonExistentTier}/Quotas/{q.id}")] + public async Task WhenADeleteRequestIsSentToTheDeleteTierQuotaEndpointWithANonExistentTierId() + { + _deleteResponse = await _client.Tiers.DeleteTierQuota("nonExistentTierId", _tierQuotaDefinitionId); + } + [Then(@"the response status code is (\d+) \(.+\)")] public void ThenTheResponseStatusCodeIs(int expectedStatusCode) { diff --git a/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/TiersStepDefinitions.cs b/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/TiersStepDefinitions.cs index d978edefb4..b8323e0995 100644 --- a/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/TiersStepDefinitions.cs +++ b/Applications/AdminApi/test/AdminApi.Tests.Integration/StepDefinitions/TiersStepDefinitions.cs @@ -11,11 +11,13 @@ namespace Backbone.AdminApi.Tests.Integration.StepDefinitions; [Binding] [Scope(Feature = "GET Tiers")] +[Scope(Feature = "GET Tiers/{id}")] [Scope(Feature = "POST Tier")] [Scope(Feature = "DELETE Tier")] internal class TiersStepDefinitions : BaseStepDefinitions { private ApiResponse? _tierResponse; + private ApiResponse? _getTierResponse; private ApiResponse? _deleteResponse; private ApiResponse? _tiersResponse; private string _existingTierName; @@ -54,6 +56,18 @@ public async Task WhenAGETRequestIsSentToTheTiersEndpoint() _tiersResponse = await _client.Tiers.ListTiers(); } + [When("a GET request is sent to the /Tiers/{t.id} endpoint")] + public async Task WhenAGETRequestIsSentToTheTiersByIdEndpoint() + { + _getTierResponse = await _client.Tiers.GetTier(_existingTierId); + } + + [When("a GET request is sent to the /Tiers/{nonExistentTierId} endpoint")] + public async Task WhenAGETRequestIsSentToTheTiersByIdEndpointWithANonExistentId() + { + _getTierResponse = await _client.Tiers.GetTier("TIRNonExistentId1231"); + } + [When("a POST request is sent to the /Tiers endpoint")] public async Task WhenAPOSTRequestIsSentToTheTiersEndpoint() { @@ -94,6 +108,15 @@ public async Task ThenTheResponseContainsATier() await _tierResponse.Should().ComplyWithSchema(); } + [Then("the response contains Tier t")] + public async Task ThenTheResponseContainsTierT() + { + _getTierResponse!.Should().BeASuccess(); + _getTierResponse!.ContentType.Should().StartWith("application/json"); + await _getTierResponse.Should().ComplyWithSchema(); + _getTierResponse.Result!.Id.Should().Be(_existingTierId); + } + [Then(@"the response status code is (\d+) \(.+\)")] public void ThenTheResponseStatusCodeIs(int expectedStatusCode) { @@ -105,12 +128,24 @@ public void ThenTheResponseStatusCodeIs(int expectedStatusCode) if (_deleteResponse != null) ((int)_deleteResponse!.Status).Should().Be(expectedStatusCode); + + if (_getTierResponse != null) + ((int)_getTierResponse!.Status).Should().Be(expectedStatusCode); } [Then(@"the response content contains an error with the error code ""([^""]+)""")] public void ThenTheResponseContentIncludesAnErrorWithTheErrorCode(string errorCode) { - _tierResponse!.Error.Should().NotBeNull(); - _tierResponse.Error!.Code.Should().Be(errorCode); + if (_tierResponse != null) + { + _tierResponse!.Error.Should().NotBeNull(); + _tierResponse.Error!.Code.Should().Be(errorCode); + } + + if (_getTierResponse != null) + { + _getTierResponse!.Error.Should().NotBeNull(); + _getTierResponse.Error!.Code.Should().Be(errorCode); + } } } diff --git a/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/Features/Identities/Self/DeletionProcess/PUT.feature b/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/Features/Identities/Self/DeletionProcess/PUT.feature new file mode 100644 index 0000000000..8a94a96ed1 --- /dev/null +++ b/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/Features/Identities/Self/DeletionProcess/PUT.feature @@ -0,0 +1,10 @@ +@Integration +Feature: PUT Identities/Self/DeletionProcesses/{id}/Approve + +User approves a deletion process + +Scenario: Approve a non-existent deletion process + Given an Identity i + When a PUT request is sent to the /Identities/Self/DeletionProcesses/{id}/Approve endpoint with a non-existent deletionProcessId + Then the response status code is 404 (Not Found) + And the response content contains an error with the error code "error.platform.recordNotFound" diff --git a/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/Features/Relationships/POST.feature b/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/Features/Relationships/POST.feature index 7e5a87a62c..70064bb371 100644 --- a/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/Features/Relationships/POST.feature +++ b/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/Features/Relationships/POST.feature @@ -1,4 +1,4 @@ -@Integration + @Integration Feature: POST Relationship User creates a Relationship diff --git a/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/StepDefinitions/IdentitiesApiStepDefinitions.cs b/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/StepDefinitions/IdentitiesApiStepDefinitions.cs index 5bf61f2119..84c0d6e78e 100644 --- a/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/StepDefinitions/IdentitiesApiStepDefinitions.cs +++ b/Applications/ConsumerApi/test/ConsumerApi.Tests.Integration/StepDefinitions/IdentitiesApiStepDefinitions.cs @@ -18,6 +18,7 @@ namespace Backbone.ConsumerApi.Tests.Integration.StepDefinitions; [Binding] [Scope(Feature = "POST Identities/Self/DeletionProcess")] +[Scope(Feature = "PUT Identities/Self/DeletionProcesses/{id}/Approve")] [Scope(Feature = "POST Identity")] internal class IdentitiesApiStepDefinitions { @@ -25,6 +26,7 @@ internal class IdentitiesApiStepDefinitions private readonly ClientCredentials _clientCredentials; private readonly HttpClient _httpClient; private ApiResponse? _startDeletionProcessResponse; + private ApiResponse? _approveDeletionProcessResponse; private ApiResponse? _identityResponse; private ApiResponse? _challengeResponse; @@ -64,6 +66,12 @@ public async Task WhenAPOSTRequestIsSentToTheIdentitiesSelfDeletionProcessEndpoi _startDeletionProcessResponse = await _sdk.Identities.StartDeletionProcess(); } + [When("a PUT request is sent to the /Identities/Self/DeletionProcesses/{id}/Approve endpoint with a non-existent deletionProcessId")] + public async Task WhenAPutRequestIsSentToTheIdentitiesSelfDeletionProcessesIdApproveEndpointWithANonExistentDeletionProcessId() + { + _approveDeletionProcessResponse = await _sdk.Identities.ApproveDeletionProcess("IDPSomeNonExistentId"); + } + [When("a POST request is sent to the /Identities endpoint with a valid signature on c")] public async Task WhenAPOSTRequestIsSentToTheIdentitiesEndpoint() { @@ -94,8 +102,17 @@ public async Task WhenAPOSTRequestIsSentToTheIdentitiesEndpoint() [Then(@"the response content contains an error with the error code ""([^""]*)""")] public void ThenTheResponseContentIncludesAnErrorWithTheErrorCode(string errorCode) { - _startDeletionProcessResponse!.Error.Should().NotBeNull(); - _startDeletionProcessResponse.Error!.Code.Should().Be(errorCode); + if (_startDeletionProcessResponse != null) + { + _startDeletionProcessResponse!.Error.Should().NotBeNull(); + _startDeletionProcessResponse.Error!.Code.Should().Be(errorCode); + } + + if (_approveDeletionProcessResponse != null) + { + _approveDeletionProcessResponse!.Error.Should().NotBeNull(); + _approveDeletionProcessResponse.Error!.Code.Should().Be(errorCode); + } } [Then("the response contains a Deletion Process")] diff --git a/Modules/Challenges/test/Challenges.Application.Tests/Tests/Identities/Commands/DeleteIdentityCommandTests/HandlerTests.cs b/Modules/Challenges/test/Challenges.Application.Tests/Tests/Identities/Commands/DeleteIdentityCommandTests/HandlerTests.cs deleted file mode 100644 index 433849cc7e..0000000000 --- a/Modules/Challenges/test/Challenges.Application.Tests/Tests/Identities/Commands/DeleteIdentityCommandTests/HandlerTests.cs +++ /dev/null @@ -1,32 +0,0 @@ -using System.Linq.Expressions; -using Backbone.Modules.Challenges.Application.Challenges.Commands.DeleteChallengesOfIdentity; -using Backbone.Modules.Challenges.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Challenges.Domain.Entities; -using Backbone.UnitTestTools.BaseClasses; -using FakeItEasy; -using Xunit; - -namespace Backbone.Modules.Challenges.Application.Tests.Tests.Identities.Commands.DeleteIdentityCommandTests; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Handler_calls_deletion_method_on_repository() - { - // Arrange - const string identityAddress = "identity-address"; - var mockChallengesRepository = A.Fake(); - var handler = CreateHandler(mockChallengesRepository); - - // Act - await handler.Handle(new DeleteChallengesOfIdentityCommand(identityAddress), CancellationToken.None); - - // Assert - A.CallTo(() => mockChallengesRepository.Delete(A>>._, A._)).MustHaveHappenedOnceExactly(); - } - - private static Handler CreateHandler(IChallengesRepository challengesRepository) - { - return new Handler(challengesRepository); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Clients/Commands/ChangeClientSecret/HandlerTests.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Clients/Commands/ChangeClientSecret/HandlerTests.cs deleted file mode 100644 index 62530995cf..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Clients/Commands/ChangeClientSecret/HandlerTests.cs +++ /dev/null @@ -1,41 +0,0 @@ -using Backbone.Modules.Devices.Application.Clients.Commands.ChangeClientSecret; -using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Devices.Domain.Aggregates.Tier; -using Backbone.Modules.Devices.Domain.Entities; -using Backbone.Tooling; -using Backbone.UnitTestTools.BaseClasses; -using FakeItEasy; -using Xunit; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Clients.Commands.ChangeClientSecret; -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Change_client_secret() - { - // Arrange - var client = new OAuthClient("some-client-id", string.Empty, TierId.Generate(), SystemTime.UtcNow, 1); - - const string newClientSecret = "New-client-secret"; - var command = new ChangeClientSecretCommand(client.ClientId, newClientSecret); - - var oAuthClientsRepository = A.Fake(); - A.CallTo(() => oAuthClientsRepository.Find(client.ClientId, A._, A._)).Returns(client); - - var handler = CreateHandler(oAuthClientsRepository); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - A.CallTo(() => oAuthClientsRepository.ChangeClientSecret(A.That.Matches(c => - c.ClientId == client.ClientId), newClientSecret - , CancellationToken.None) - ).MustHaveHappenedOnceExactly(); - } - - private Handler CreateHandler(IOAuthClientsRepository oAuthClientsRepository) - { - return new Handler(oAuthClientsRepository); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Clients/Commands/UpdateClient/HandlerTests.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Clients/Commands/UpdateClient/HandlerTests.cs deleted file mode 100644 index 70059ed4bb..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Clients/Commands/UpdateClient/HandlerTests.cs +++ /dev/null @@ -1,166 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Exceptions; -using Backbone.BuildingBlocks.Domain; -using Backbone.Modules.Devices.Application.Clients.Commands.UpdateClient; -using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Devices.Application.Tests.Extensions; -using Backbone.Modules.Devices.Domain.Aggregates.Tier; -using Backbone.Modules.Devices.Domain.Entities; -using Backbone.Tooling; -using Backbone.UnitTestTools.BaseClasses; -using FakeItEasy; -using FluentAssertions; -using Xunit; -using ApplicationException = Backbone.BuildingBlocks.Application.Abstractions.Exceptions.ApplicationException; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Clients.Commands.UpdateClient; -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Change_Default_Tier() - { - // Arrange - var client = new OAuthClient("some-client-id", string.Empty, TierId.Generate(), SystemTime.UtcNow, 1); - - var newDefaultTier = new Tier(TierName.Create("new-default-tier").Value); - - var command = new UpdateClientCommand(client.ClientId, newDefaultTier.Id, 1); - - var oAuthClientsRepository = A.Fake(); - A.CallTo(() => oAuthClientsRepository.Find(client.ClientId, A._, A._)).Returns(client); - - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.CountByClientId(client.ClientId, A._)).Returns(0); - - var tiersRepository = A.Fake(); - A.CallTo(() => tiersRepository.ExistsWithId(newDefaultTier.Id, A._)).Returns(true); - - var handler = CreateHandler(oAuthClientsRepository, identitiesRepository, tiersRepository); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - A.CallTo(() => oAuthClientsRepository.Update(A.That.Matches(c => - c.ClientId == client.ClientId && - c.DefaultTier == newDefaultTier.Id) - , CancellationToken.None) - ).MustHaveHappenedOnceExactly(); - } - - [Fact] - public async Task Change_Default_Tier_With_Inexistent_Tier() - { - // Arrange - var client = new OAuthClient("some-client-id", string.Empty, TierId.Generate(), SystemTime.UtcNow, 1); - - var newDefaultTier = new Tier(TierName.Create("new-default-tier").Value); - - var command = new UpdateClientCommand(client.ClientId, newDefaultTier.Id, 1); - - var oAuthClientsRepository = A.Fake(); - A.CallTo(() => oAuthClientsRepository.Find(client.ClientId, A._, A._)).Returns(client); - - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.CountByClientId(client.ClientId, A._)).Returns(0); - - var tiersRepository = A.Fake(); - A.CallTo(() => tiersRepository.ExistsWithId(newDefaultTier.Id, A._)).Returns(false); - - var handler = CreateHandler(oAuthClientsRepository, identitiesRepository, tiersRepository); - - // Act - var acting = async () => await handler.Handle(command, CancellationToken.None); - - // Assert - await acting.Should().ThrowAsync().WithErrorCode("error.platform.validation.device.tierIdInvalidOrDoesNotExist"); - } - - [Fact] - public async Task Change_Default_Tier_Of_Inexistent_Client() - { - // Arrange - var client = new OAuthClient("some-client-id", string.Empty, TierId.Generate(), SystemTime.UtcNow, 1); - - var newDefaultTier = new Tier(TierName.Create("new-default-tier").Value); - - var command = new UpdateClientCommand(client.ClientId, newDefaultTier.Id, 1); - - var oAuthClientsRepository = A.Fake(); - A.CallTo(() => oAuthClientsRepository.Find(client.ClientId, A._, A._)).Returns(null); - - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.CountByClientId(client.ClientId, A._)).Returns(0); - - var tiersRepository = A.Fake(); - A.CallTo(() => tiersRepository.ExistsWithId(newDefaultTier.Id, A._)).Returns(true); - - var handler = CreateHandler(oAuthClientsRepository, identitiesRepository, tiersRepository); - - // Act - var acting = async () => await handler.Handle(command, CancellationToken.None); - - // Assert - await acting.Should().ThrowAsync(); - } - - [Fact] - public async Task Change_Max_Identities() - { - // Arrange - var client = new OAuthClient("some-client-id", string.Empty, TierId.Generate(), SystemTime.UtcNow, 1); - - var command = new UpdateClientCommand(client.ClientId, client.DefaultTier, 2); - - var oAuthClientsRepository = A.Fake(); - A.CallTo(() => oAuthClientsRepository.Find(client.ClientId, A._, A._)).Returns(client); - - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.CountByClientId(client.ClientId, A._)).Returns(0); - - var tiersRepository = A.Fake(); - A.CallTo(() => tiersRepository.ExistsWithId(client.DefaultTier, A._)).Returns(true); - - var handler = CreateHandler(oAuthClientsRepository, identitiesRepository, tiersRepository); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - A.CallTo(() => oAuthClientsRepository.Update(A.That.Matches(c => - c.ClientId == client.ClientId && - c.MaxIdentities == 2) - , CancellationToken.None) - ).MustHaveHappenedOnceExactly(); - } - - [Fact] - public async Task Change_Max_Identities_Of_Inexistent_Client() - { - // Arrange - var client = new OAuthClient("some-client-id", string.Empty, TierId.Generate(), SystemTime.UtcNow, 1); - - var command = new UpdateClientCommand(client.ClientId, client.DefaultTier, 2); - - var oAuthClientsRepository = A.Fake(); - A.CallTo(() => oAuthClientsRepository.Find(client.ClientId, A._, A._)).Returns(null); - - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.CountByClientId(client.ClientId, A._)).Returns(0); - - var tiersRepository = A.Fake(); - A.CallTo(() => tiersRepository.ExistsWithId(client.DefaultTier, A._)).Returns(true); - - var handler = CreateHandler(oAuthClientsRepository, identitiesRepository, tiersRepository); - - // Act - var acting = async () => await handler.Handle(command, CancellationToken.None); - - // Assert - await acting.Should().ThrowAsync(); - } - - private static Handler CreateHandler(IOAuthClientsRepository oAuthClientsRepository, IIdentitiesRepository identitiesRepository, ITiersRepository tiersRepository) - { - return new Handler(oAuthClientsRepository, identitiesRepository, tiersRepository); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Devices/Commands/DeleteDevice/HandlerTests.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Devices/Commands/DeleteDevice/HandlerTests.cs deleted file mode 100644 index f65ceb9893..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Devices/Commands/DeleteDevice/HandlerTests.cs +++ /dev/null @@ -1,111 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Exceptions; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Devices.Application.Devices.Commands.DeleteDevice; -using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Devices.Domain.Entities.Identities; -using Backbone.Tooling; -using Backbone.UnitTestTools.BaseClasses; -using FakeItEasy; -using FluentAssertions; -using Microsoft.Extensions.Logging; -using Xunit; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Devices.Commands.DeleteDevice; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Deletes_unOnboarded_device_owned_by_identity() - { - // Arrange - var identity = TestDataGenerator.CreateIdentity(); - var unOnboardedDevice = CreateUnOnboardedDevice(identity); - var onboardedDevice = CreateOnboardedDevice(identity); - - var mockIdentitiesRepository = A.Fake(); - A.CallTo(() => mockIdentitiesRepository.GetDeviceById(unOnboardedDevice.Id, A._, A._)).Returns(unOnboardedDevice); - A.CallTo(() => mockIdentitiesRepository.GetDeviceById(onboardedDevice.Id, A._, A._)).Returns(onboardedDevice); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(identity.Address); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(onboardedDevice.Id); - - var handler = CreateHandler(mockIdentitiesRepository, fakeUserContext); - - var deleteDeviceCommand = new DeleteDeviceCommand - { - DeviceId = unOnboardedDevice.Id - }; - - var utcNow = DateTime.Parse("2000-01-01"); - SystemTime.Set(utcNow); - - // Act - await handler.Handle(deleteDeviceCommand, CancellationToken.None); - - // Assert - unOnboardedDevice.DeletedAt.Should().NotBeNull(); - unOnboardedDevice.DeletedAt.Should().Be(utcNow); - unOnboardedDevice.DeletedByDevice.Should().Be(onboardedDevice.Id); - - A.CallTo(() => mockIdentitiesRepository.Update( - unOnboardedDevice, - A._ - )).MustHaveHappenedOnceExactly(); - } - - [Fact] - public void Throws_if_given_device_id_does_not_exist() - { - // Arrange - var activeDevice = CreateOnboardedDevice(); - const string nonExistentDeviceId = "DVCnonExistingIdxxxx"; - - var mockIdentitiesRepository = A.Fake(); - A.CallTo(() => mockIdentitiesRepository.GetDeviceById(activeDevice.Id, A._, A._)).Returns(activeDevice); - - var handler = CreateHandler(mockIdentitiesRepository); - - var deleteDeviceCommand = new DeleteDeviceCommand - { - DeviceId = nonExistentDeviceId - }; - - // Act - var action = async () => await handler.Handle(deleteDeviceCommand, CancellationToken.None); - - // Assert - var exception = action.Should().ThrowAsync(); - exception.WithMessage(nameof(Device)); - } - - #region helpers - - private static Device CreateUnOnboardedDevice(Identity identity) - { - var unOnboardedDevice = new Device(identity, CommunicationLanguage.DEFAULT_LANGUAGE); - var unOnboardedDeviceUser = new ApplicationUser(identity, CommunicationLanguage.DEFAULT_LANGUAGE, unOnboardedDevice.Id); - unOnboardedDevice.User = unOnboardedDeviceUser; - - return unOnboardedDevice; - } - - private static Device CreateOnboardedDevice(Identity? identity = null) - { - identity ??= TestDataGenerator.CreateIdentity(); - var onboardedDevice = new Device(identity, CommunicationLanguage.DEFAULT_LANGUAGE); - var onboardedDeviceUser = new ApplicationUser(identity, CommunicationLanguage.DEFAULT_LANGUAGE, onboardedDevice.Id); - onboardedDevice.User = onboardedDeviceUser; - onboardedDevice.User.LoginOccurred(); - - return onboardedDevice; - } - - private static Handler CreateHandler(IIdentitiesRepository mockIdentitiesRepository, IUserContext? fakeUserContext = null) - { - fakeUserContext ??= A.Dummy(); - return new Handler(mockIdentitiesRepository, fakeUserContext, A.Dummy>()); - } - - #endregion -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Devices/Commands/UpdateActiveDevice/HandlerTests.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Devices/Commands/UpdateActiveDevice/HandlerTests.cs deleted file mode 100644 index 8a5d6f7818..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Devices/Commands/UpdateActiveDevice/HandlerTests.cs +++ /dev/null @@ -1,79 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Exceptions; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.DevelopmentKit.Identity.ValueObjects; -using Backbone.Modules.Devices.Application.Devices.Commands.UpdateActiveDevice; -using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Devices.Domain.Entities.Identities; -using Backbone.UnitTestTools.BaseClasses; -using FakeItEasy; -using FluentAssertions; -using Microsoft.Extensions.Logging; -using Xunit; -using Handler = Backbone.Modules.Devices.Application.Devices.Commands.UpdateActiveDevice.Handler; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Devices.Commands.UpdateActiveDevice; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Updates_device_with_values_sent() - { - // Arrange - var activeDevice = CreateDevice(); - - var mockIdentitiesRepository = A.Fake(); - A.CallTo(() => mockIdentitiesRepository.GetDeviceById(activeDevice.Id, A._, A._)).Returns(activeDevice); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice.Id); - - var handler = CreateHandler(mockIdentitiesRepository, fakeUserContext); - - var expectedCommunicationLanguage = CommunicationLanguage.Create("de").Value; - var updateActiveDeviceCommand = new UpdateActiveDeviceCommand - { - CommunicationLanguage = expectedCommunicationLanguage - }; - - // Act - await handler.Handle(updateActiveDeviceCommand, CancellationToken.None); - - // Assert - A.CallTo(() => mockIdentitiesRepository.Update( - A.That.Matches(d => d.CommunicationLanguage == updateActiveDeviceCommand.CommunicationLanguage), - A._ - )).MustHaveHappenedOnceExactly(); - } - - [Fact] - public void Throws_if_given_device_id_does_not_exist() - { - // Arrange - var mockIdentitiesRepository = A.Fake(); - A.CallTo(() => mockIdentitiesRepository.GetDeviceById(A._, A._, A._)).Returns((Device?)null); - - var handler = CreateHandler(mockIdentitiesRepository); - var updateActiveDeviceCommand = new UpdateActiveDeviceCommand - { - CommunicationLanguage = "de" - }; - - // Act - var acting = async () => await handler.Handle(updateActiveDeviceCommand, CancellationToken.None); - - // Assert - acting.Should().ThrowAsync().WithMessage(nameof(Device)); - } - - private static Device CreateDevice() - { - var identity = TestDataGenerator.CreateIdentityWithOneDevice(); - return identity.Devices.First(); - } - - private static Handler CreateHandler(IIdentitiesRepository mockIdentitiesRepository, IUserContext? fakeUserContext = null) - { - fakeUserContext ??= A.Dummy(); - return new Handler(fakeUserContext, A.Dummy>(), mockIdentitiesRepository); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetDeletionProcessesAuditLogs/FindDeletionProcessAuditLogsByAddressStubRepository.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetDeletionProcessesAuditLogs/FindDeletionProcessAuditLogsByAddressStubRepository.cs deleted file mode 100644 index 85d03f57a6..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetDeletionProcessesAuditLogs/FindDeletionProcessAuditLogsByAddressStubRepository.cs +++ /dev/null @@ -1,88 +0,0 @@ -using System.Linq.Expressions; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.Persistence.Database; -using Backbone.BuildingBlocks.Application.Pagination; -using Backbone.DevelopmentKit.Identity.ValueObjects; -using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Devices.Domain.Entities.Identities; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Identities.Queries.GetDeletionProcessesAuditLogs; - -public class FindDeletionProcessAuditLogsByAddressStubRepository : IIdentitiesRepository -{ - private readonly IEnumerable _identityDeletionProcessAuditLogs; - - public FindDeletionProcessAuditLogsByAddressStubRepository(IEnumerable identityDeletionProcessAuditLogs) - { - _identityDeletionProcessAuditLogs = identityDeletionProcessAuditLogs; - } - - public Task Exists(IdentityAddress address, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task> FindAllWithDeletionProcessInStatus(DeletionProcessStatus status, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task CountByClientId(string clientId, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task AddUser(ApplicationUser user, string password) - { - throw new NotSupportedException(); - } - - public Task> FindAll(PaginationFilter paginationFilter, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task> FindAllDevicesOfIdentity(IdentityAddress identity, IEnumerable ids, PaginationFilter paginationFilter, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task GetDeviceById(DeviceId deviceId, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task Update(Device device, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task> GetIdentityDeletionProcessAuditLogsByAddress(byte[] identityAddressHash, CancellationToken cancellationToken) - { - return Task.FromResult(_identityDeletionProcessAuditLogs); - } - - public Task AddDeletionProcessAuditLogEntry(IdentityDeletionProcessAuditLogEntry auditLogEntry) - { - throw new NotSupportedException(); - } - - public Task Update(Identity identity, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task FindByAddress(IdentityAddress address, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task> Find(Expression> filter, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task Delete(Expression> filter, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetIdentity/FindByAddressStubRepository.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetIdentity/FindByAddressStubRepository.cs deleted file mode 100644 index eb7dd14298..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetIdentity/FindByAddressStubRepository.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Linq.Expressions; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.Persistence.Database; -using Backbone.BuildingBlocks.Application.Pagination; -using Backbone.DevelopmentKit.Identity.ValueObjects; -using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Devices.Domain.Entities.Identities; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Identities.Queries.GetIdentity; - -public class FindByAddressStubRepository : IIdentitiesRepository -{ - private readonly Identity _identity; - - public FindByAddressStubRepository(Identity identity) - { - _identity = identity; - } - - public Task Exists(IdentityAddress address, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task> FindAllWithDeletionProcessInStatus(DeletionProcessStatus status, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task CountByClientId(string clientId, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task AddUser(ApplicationUser user, string password) - { - throw new NotSupportedException(); - } - - public Task> FindAllDevicesOfIdentity(IdentityAddress identity, IEnumerable ids, PaginationFilter paginationFilter, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task GetDeviceById(DeviceId deviceId, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task Update(Device device, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task> GetIdentityDeletionProcessAuditLogsByAddress(byte[] identityAddressHash, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task AddDeletionProcessAuditLogEntry(IdentityDeletionProcessAuditLogEntry auditLogEntry) - { - throw new NotSupportedException(); - } - - public Task Update(Identity identity, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task FindByAddress(IdentityAddress address, CancellationToken cancellationToken, bool track = false) - { - return Task.FromResult((Identity?)_identity); - } - - public Task> Find(Expression> filter, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task Delete(Expression> filter, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetIdentity/HandlerTests.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetIdentity/HandlerTests.cs deleted file mode 100644 index 9c584bf5b7..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/GetIdentity/HandlerTests.cs +++ /dev/null @@ -1,58 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Exceptions; -using Backbone.DevelopmentKit.Identity.ValueObjects; -using Backbone.Modules.Devices.Application.Identities.Queries.GetIdentity; -using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Devices.Domain.Entities.Identities; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Extensions; -using FakeItEasy; -using FluentAssertions; -using Xunit; -using static Backbone.UnitTestTools.Data.TestDataGenerator; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Identities.Queries.GetIdentity; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Gets_identity_by_address() - { - // Arrange - var identity = new Identity(CreateRandomDeviceId(), CreateRandomIdentityAddress(), [1, 1, 1, 1, 1], TestDataGenerator.CreateRandomTierId(), 1); - - var handler = CreateHandler(new FindByAddressStubRepository(identity)); - - // Act - var result = await handler.Handle(new GetIdentityQuery(identity.Address), CancellationToken.None); - - // Assert - result.ClientId.Should().Be(identity.ClientId); - result.Address.Should().Be(identity.Address); - result.PublicKey.Should().BeEquivalentTo(identity.PublicKey); - result.TierId.Should().BeEquivalentTo(identity.TierId); - result.IdentityVersion.Should().Be(1); - } - - [Fact] - public void Fails_when_no_identity_found() - { - // Arrange - var identityRepository = A.Fake(); - A.CallTo(() => identityRepository.FindByAddress(A._, A._, A._)).Returns(null); - - var handler = CreateHandler(identityRepository); - - // Act - Func acting = async () => await handler.Handle(new GetIdentityQuery("some-inexistent-identity-address"), CancellationToken.None); - - // Assert - var exception = acting.Should().AwaitThrowAsync().Which; - exception.Message.Should().StartWith("Identity"); - exception.Code.Should().Be("error.platform.recordNotFound"); - } - - private Handler CreateHandler(IIdentitiesRepository identitiesRepository) - { - return new Handler(identitiesRepository); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/ListIdentities/FindAllStubRepository.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/ListIdentities/FindAllStubRepository.cs deleted file mode 100644 index f5920502a4..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/ListIdentities/FindAllStubRepository.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System.Linq.Expressions; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.Persistence.Database; -using Backbone.BuildingBlocks.Application.Pagination; -using Backbone.DevelopmentKit.Identity.ValueObjects; -using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Devices.Domain.Entities.Identities; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Identities.Queries.ListIdentities; - -public class FindAllStubRepository : IIdentitiesRepository -{ - private readonly IEnumerable _identities; - - public FindAllStubRepository(IEnumerable identities) - { - _identities = identities; - } - - public Task Exists(IdentityAddress address, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task> FindAllWithDeletionProcessInStatus(DeletionProcessStatus status, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task CountByClientId(string clientId, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task AddUser(ApplicationUser user, string password) - { - throw new NotSupportedException(); - } - - public Task> FindAllDevicesOfIdentity(IdentityAddress identity, IEnumerable ids, PaginationFilter paginationFilter, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task GetDeviceById(DeviceId deviceId, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task Update(Device device, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task> GetIdentityDeletionProcessAuditLogsByAddress(byte[] identityAddressHash, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task AddDeletionProcessAuditLogEntry(IdentityDeletionProcessAuditLogEntry auditLogEntry) - { - throw new NotSupportedException(); - } - - public Task Update(Identity identity, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task FindByAddress(IdentityAddress address, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task> Find(Expression> filter, CancellationToken cancellationToken, bool track = false) - { - return Task.FromResult(_identities); - } - - public Task Delete(Expression> filter, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/ListIdentities/HandlerTests.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/ListIdentities/HandlerTests.cs deleted file mode 100644 index a2ea0c1ca0..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Identities/Queries/ListIdentities/HandlerTests.cs +++ /dev/null @@ -1,81 +0,0 @@ -using Backbone.Modules.Devices.Application.Identities.Queries.ListIdentities; -using Backbone.Modules.Devices.Domain.Entities.Identities; -using Backbone.UnitTestTools.BaseClasses; -using FluentAssertions; -using Xunit; -using static Backbone.UnitTestTools.Data.TestDataGenerator; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Identities.Queries.ListIdentities; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Returns_an_empty_list_when_no_identities_exist() - { - // Arrange - var identities = new List(); - var handler = CreateHandler(new FindAllStubRepository(identities)); - - // Act - var result = await handler.Handle(new ListIdentitiesQuery(), CancellationToken.None); - - // Assert - result.Should().HaveCount(identities.Count); - } - - [Fact] - public async Task? Returns_a_list_of_all_existing_identities() - { - // Arrange - List identities = - [ - new Identity(CreateRandomDeviceId(), - CreateRandomIdentityAddress(), - CreateRandomBytes(), - TestDataGenerator.CreateRandomTierId(), - 1), - - new Identity(CreateRandomDeviceId(), - CreateRandomIdentityAddress(), - CreateRandomBytes(), - TestDataGenerator.CreateRandomTierId(), - 1) - ]; - var handler = CreateHandler(new FindAllStubRepository(identities)); - - // Act - var result = await handler.Handle(new ListIdentitiesQuery(), CancellationToken.None); - - // Assert - result.Should().HaveCount(identities.Count); - } - - [Fact] - public async Task Returned_identities_have_all_properties_filled_as_expected() - { - // Arrange - var expectedClientId = CreateRandomDeviceId(); - var expectedAddress = CreateRandomIdentityAddress(); - var expectedTierId = TestDataGenerator.CreateRandomTierId(); - List identities = [new Identity(expectedClientId, expectedAddress, [], expectedTierId, 1)]; - - var handler = CreateHandler(new FindAllStubRepository(identities)); - - // Act - var result = await handler.Handle(new ListIdentitiesQuery(), CancellationToken.None); - - // Assert - result.Should().HaveCount(1); - result.First().ClientId.Should().Be(expectedClientId); - result.First().Address.Should().Be(expectedAddress); - result.First().PublicKey.Should().BeEquivalentTo(Array.Empty()); - result.First().TierId.Should().BeEquivalentTo(expectedTierId); - result.First().Status.Should().Be(IdentityStatus.Active); - result.First().IdentityVersion.Should().Be(1); - } - - private Handler CreateHandler(FindAllStubRepository findAllStubRepository) - { - return new Handler(findAllStubRepository); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Commands/CreateTier/HandlerTests.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Commands/CreateTier/HandlerTests.cs deleted file mode 100644 index fb919624dd..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Commands/CreateTier/HandlerTests.cs +++ /dev/null @@ -1,60 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; -using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Devices.Application.Tests.Extensions; -using Backbone.Modules.Devices.Application.Tiers.Commands.CreateTier; -using Backbone.Modules.Devices.Domain.Aggregates.Tier; -using Backbone.UnitTestTools.BaseClasses; -using FakeItEasy; -using FluentAssertions; -using Microsoft.Extensions.Logging; -using Xunit; -using ApplicationException = Backbone.BuildingBlocks.Application.Abstractions.Exceptions.ApplicationException; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Tiers.Commands.CreateTier; - -public class HandlerTests : AbstractTestsBase -{ - private readonly Handler _handler; - private readonly ITiersRepository _tierRepository; - - public HandlerTests() - { - _tierRepository = A.Fake(); - _handler = CreateHandler(); - } - - private Handler CreateHandler() - { - var logger = A.Fake>(); - return new Handler(_tierRepository, logger); - } - - [Fact] - public async Task Creates_a_tier_when_properties_are_valid() - { - // Arrange - var expectedTierName = TierName.Create("my-tier-name"); - var expectedTier = new Tier(expectedTierName.Value); - A.CallTo(() => _tierRepository.AddAsync(expectedTier, CancellationToken.None)).Returns(Task.FromResult(expectedTier)); - - // Act - var result = await _handler.Handle(new CreateTierCommand(expectedTierName.Value), CancellationToken.None); - - // Assert - result.Id.Should().NotBeNull(); - result.Name.Should().Be(expectedTierName.Value); - } - - [Fact] - public async Task Fails_to_create_a_tier_when_tier_name_already_exists() - { - // Arrange - A.CallTo(() => _tierRepository.ExistsWithName(A._, CancellationToken.None)).Returns(Task.FromResult(true)); - - // Act - var acting = async () => await _handler.Handle(new CreateTierCommand("my-tier-name"), CancellationToken.None); - - // Assert - await acting.Should().ThrowAsync().WithErrorCode("error.platform.validation.device.tierNameAlreadyExists"); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Queries/ListTiers/FindAllStubRepository.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Queries/ListTiers/FindAllStubRepository.cs deleted file mode 100644 index db6f1a6976..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Queries/ListTiers/FindAllStubRepository.cs +++ /dev/null @@ -1,71 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.Persistence.Database; -using Backbone.BuildingBlocks.Application.Pagination; -using Backbone.Modules.Devices.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Devices.Domain.Aggregates.Tier; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Tiers.Queries.ListTiers; - -public class FindAllStubRepository : ITiersRepository -{ - private readonly DbPaginationResult _tiers; - - public FindAllStubRepository(DbPaginationResult tiers) - { - _tiers = tiers; - } - - public Task AddAsync(Tier tier, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task ExistsWithId(TierId tierId, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task ExistsWithName(TierName tierName, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task> FindAll(PaginationFilter paginationFilter, CancellationToken cancellationToken) - { - return Task.FromResult(_tiers); - } - - public Task FindById(TierId tierId, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task FindByName(TierName tierName, CancellationToken cancellationToken, bool track = false) - { - throw new NotSupportedException(); - } - - public Task> FindByIds(IEnumerable tiers, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task FindBasicTier(CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task GetNumberOfClientsWithDefaultTier(Tier tier, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task GetNumberOfIdentitiesAssignedToTier(Tier tier, CancellationToken cancellationToken) - { - throw new NotSupportedException(); - } - - public Task Remove(Tier tier) - { - throw new NotSupportedException(); - } -} diff --git a/Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Queries/ListTiers/HandlerTests.cs b/Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Queries/ListTiers/HandlerTests.cs deleted file mode 100644 index fd14ac8cdf..0000000000 --- a/Modules/Devices/test/Devices.Application.Tests/Tests/Tiers/Queries/ListTiers/HandlerTests.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.Persistence.Database; -using Backbone.BuildingBlocks.Application.Pagination; -using Backbone.Modules.Devices.Application.Tiers.Queries.ListTiers; -using Backbone.Modules.Devices.Domain.Aggregates.Tier; -using Backbone.UnitTestTools.BaseClasses; -using FluentAssertions; -using FluentAssertions.Execution; -using Xunit; - -namespace Backbone.Modules.Devices.Application.Tests.Tests.Tiers.Queries.ListTiers; - -public class HandlerTests : AbstractTestsBase -{ - public HandlerTests() - { - AssertionScope.Current.FormattingOptions.MaxLines = 1000; - } - - [Fact] - public async Task Returns_an_empty_list_when_no_tiers_exist() - { - // Arrange - var tiersList = new List(); - var request = new PaginationFilter() { PageSize = 5 }; - var handler = CreateHandler(new FindAllStubRepository(MakeDbPaginationResult(tiersList))); - - // Act - var result = await handler.Handle(new ListTiersQuery(request), CancellationToken.None); - - // Assert - result.Should().HaveCount(0); - } - - [Fact] - public async Task Returns_a_list_of_all_existing_tiers() - { - // Arrange - var request = new PaginationFilter(); - List tiersList = - [ - new Tier(TierName.Create("my-tier-name-1").Value), - new Tier(TierName.Create("my-tier-name-2").Value) - ]; - - var handler = CreateHandler(new FindAllStubRepository(MakeDbPaginationResult(tiersList))); - - // Act - var result = await handler.Handle(new ListTiersQuery(request), CancellationToken.None); - - // Assert - result.Should().HaveCount(2); - } - - [Fact] - public async Task Returned_tiers_have_all_properties_filled_as_expected() - { - // Arrange - var request = new PaginationFilter(); - var expectedName = TierName.Create("my-tier-name").Value; - List tiersList = [new Tier(expectedName)]; - - var handler = CreateHandler(new FindAllStubRepository(MakeDbPaginationResult(tiersList))); - - // Act - var result = await handler.Handle(new ListTiersQuery(request), CancellationToken.None); - - // Assert - result.Should().HaveCount(1); - result.First().Id.Should().NotBeNull(); - result.First().Name.Should().Be(expectedName); - } - - private Handler CreateHandler(FindAllStubRepository findAllStubRepository) - { - return new Handler(findAllStubRepository); - } - - private DbPaginationResult MakeDbPaginationResult(List tiers) - { - return new DbPaginationResult(tiers, tiers.Count); - } -} diff --git a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Identities/ListQuotasForIdentity/HandlerTests.cs b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Identities/ListQuotasForIdentity/HandlerTests.cs deleted file mode 100644 index 4a89d021e8..0000000000 --- a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Identities/ListQuotasForIdentity/HandlerTests.cs +++ /dev/null @@ -1,70 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Quotas.Application.Identities.Queries.ListQuotasForIdentity; -using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Quotas.Domain.Aggregates.Identities; -using Backbone.Modules.Quotas.Domain.Aggregates.Metrics; -using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; -using Backbone.UnitTestTools.BaseClasses; -using FakeItEasy; -using FluentAssertions; -using Xunit; -using static Backbone.UnitTestTools.Data.TestDataGenerator; - -namespace Backbone.Modules.Quotas.Application.Tests.Tests.Identities.ListQuotasForIdentity; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Returns_individual_and_tier_quotas_for_identity() - { - // Arrange - var metric1 = new Metric(MetricKey.NumberOfSentMessages, "Number Of Sent Messages"); - var metric2 = new Metric(MetricKey.NumberOfTokens, "Number Of Tokens"); - var identity = new Identity(CreateRandomIdentityAddress(), TierId.Parse("tier-id")); - - identity.AssignTierQuotaFromDefinition(new TierQuotaDefinition(metric1.Key, 5, QuotaPeriod.Month)); - identity.CreateIndividualQuota(metric2.Key, 5, QuotaPeriod.Month); - identity.CreateIndividualQuota(metric1.Key, 10, QuotaPeriod.Week); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(identity.Address); - - var fakeIdentitiesRepository = A.Fake(); - A.CallTo(() => fakeIdentitiesRepository.Find(identity.Address, A._, A._)).Returns(identity); - - var fakeMetricCalculatorFactory = new FakeMetricCalculatorFactory(numberOfSentMessages: 1, numberOfTokens: 2); - - var handler = new Handler(fakeUserContext, fakeIdentitiesRepository, fakeMetricCalculatorFactory); - - // Act - var quotaGroupDtOs = (await handler.Handle(new ListQuotasForIdentityQuery(), CancellationToken.None)).ToList(); - - // Assert - quotaGroupDtOs.Should().HaveCount(2); - - quotaGroupDtOs.Should().ContainSingle(qg => qg.MetricKey == metric1.Key.Value); - quotaGroupDtOs.Should().ContainSingle(qg => qg.MetricKey == metric2.Key.Value); - - var metric1QuotaGroup = quotaGroupDtOs.Single(qg => qg.MetricKey == metric1.Key.Value); - var metric2QuotaGroup = quotaGroupDtOs.Single(qg => qg.MetricKey == metric2.Key.Value); - - metric1QuotaGroup.Quotas.Should().HaveCount(2); - metric2QuotaGroup.Quotas.Should().HaveCount(1); - - var tierQuota = metric1QuotaGroup.Quotas.Single(q => q.Source == QuotaSource.Tier && q.MetricKey == metric1.Key.Value); - var individualQuotaTokens = metric2QuotaGroup.Quotas.Single(q => q.Source == QuotaSource.Individual && q.MetricKey == metric2.Key.Value); - var individualQuotaMessages = metric1QuotaGroup.Quotas.Single(q => q.Source == QuotaSource.Individual && q.MetricKey == metric1.Key.Value); - - tierQuota.Max.Should().Be(5); - tierQuota.Usage.Should().Be(1); - tierQuota.Period.Should().Be("Month"); - - individualQuotaTokens.Max.Should().Be(5); - individualQuotaTokens.Usage.Should().Be(2); - individualQuotaTokens.Period.Should().Be("Month"); - - individualQuotaMessages.Max.Should().Be(10); - individualQuotaMessages.Usage.Should().Be(1); - individualQuotaMessages.Period.Should().Be("Week"); - } -} diff --git a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Identities/Queries/GetIdentity/HandlerTests.cs b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Identities/Queries/GetIdentity/HandlerTests.cs deleted file mode 100644 index b271d6bcc9..0000000000 --- a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Identities/Queries/GetIdentity/HandlerTests.cs +++ /dev/null @@ -1,88 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Exceptions; -using Backbone.Modules.Quotas.Application.Identities.Queries.GetIdentity; -using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Quotas.Application.Tests.TestDoubles; -using Backbone.Modules.Quotas.Domain.Aggregates.Identities; -using Backbone.Modules.Quotas.Domain.Aggregates.Metrics; -using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; -using Backbone.Modules.Quotas.Domain.Metrics; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Extensions; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Quotas.Application.Tests.Tests.Identities.Queries.GetIdentity; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Gets_identity_quotas_by_address() - { - // Arrange - var metric = new Metric(MetricKey.NumberOfSentMessages, "Number Of Sent Messages"); - var identity = new Identity("some-identity-address", TierId.Parse("tier-id")); - - const int max = 5; - const QuotaPeriod period = QuotaPeriod.Month; - - identity.AssignTierQuotaFromDefinition(new TierQuotaDefinition(metric.Key, max, period)); - identity.CreateIndividualQuota(metric.Key, max, period); - - var stubMetricsRepository = new FindAllWithKeysMetricsStubRepository(new List { metric }); - - var stubIdentitiesRepository = A.Fake(); - A.CallTo(() => stubIdentitiesRepository.Find(A._, A._, A._)).Returns(identity); - - var handler = CreateHandler(stubIdentitiesRepository, stubMetricsRepository); - - // Act - var result = await handler.Handle(new GetIdentityQuery(identity.Address), CancellationToken.None); - - // Assert - result.Address.Should().Be(identity.Address); - result.Quotas.Should().HaveCount(2); - - result.Quotas.First().Max.Should().Be(max); - result.Quotas.First().Period.Should().Be(period.ToString()); - result.Quotas.First().Source.Should().Be(QuotaSource.Individual); - result.Quotas.First().Metric.Key.Should().Be(metric.Key.Value); - result.Quotas.First().Metric.DisplayName.Should().Be(metric.DisplayName); - - result.Quotas.Second().Max.Should().Be(max); - result.Quotas.Second().Period.Should().Be(period.ToString()); - result.Quotas.Second().Source.Should().Be(QuotaSource.Tier); - result.Quotas.Second().Metric.Key.Should().Be(metric.Key.Value); - result.Quotas.Second().Metric.DisplayName.Should().Be(metric.DisplayName); - } - - [Fact] - public void Fails_when_no_identity_found() - { - // Arrange - var stubIdentitiesRepository = A.Fake(); - A.CallTo(() => stubIdentitiesRepository.Find(A._, A._, A._)).Returns((Identity?)null); - - var handler = CreateHandler(stubIdentitiesRepository); - - // Act - Func acting = async () => await handler.Handle(new GetIdentityQuery("some-inexistent-identity-address"), CancellationToken.None); - - // Assert - var exception = acting.Should().AwaitThrowAsync().Which; - exception.Message.Should().StartWith("Identity"); - exception.Code.Should().Be("error.platform.recordNotFound"); - } - - private static Handler CreateHandler(IIdentitiesRepository identitiesRepository) - { - var dummyMetricsRepository = A.Dummy(); - return CreateHandler(identitiesRepository, dummyMetricsRepository); - } - - private static Handler CreateHandler(IIdentitiesRepository identitiesRepository, IMetricsRepository metricsRepository) - { - var dummyMetricCalculatorFactory = A.Dummy(); - return new Handler(identitiesRepository, metricsRepository, dummyMetricCalculatorFactory); - } -} diff --git a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForIdentity/HandlerTests.cs b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForIdentity/HandlerTests.cs index 7871d793a8..d968537a16 100644 --- a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForIdentity/HandlerTests.cs +++ b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForIdentity/HandlerTests.cs @@ -1,7 +1,4 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Exceptions; -using Backbone.BuildingBlocks.Domain; -using Backbone.DevelopmentKit.Identity.ValueObjects; -using Backbone.Modules.Quotas.Application.Identities.Commands.CreateQuotaForIdentity; +using Backbone.Modules.Quotas.Application.Identities.Commands.CreateQuotaForIdentity; using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; using Backbone.Modules.Quotas.Application.Metrics; using Backbone.Modules.Quotas.Application.Tests.TestDoubles; @@ -9,9 +6,7 @@ using Backbone.Modules.Quotas.Domain.Aggregates.Metrics; using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Extensions; using FakeItEasy; -using FluentAssertions; using Microsoft.Extensions.Logging; using Xunit; using static Backbone.UnitTestTools.Data.TestDataGenerator; @@ -21,80 +16,6 @@ namespace Backbone.Modules.Quotas.Application.Tests.Tests.Quotas.CreateQuotaForI public class HandlerTests : AbstractTestsBase { - [Fact] - public async Task Creates_quota_for_identity() - { - // Arrange - const int max = 5; - const QuotaPeriod period = QuotaPeriod.Month; - var metricKey = MetricKey.NumberOfSentMessages.Value; - - var tierId = TierId.Parse("TIRsomeTierId1111111"); - var identity = new Identity(CreateRandomIdentityAddress(), tierId); - var command = new CreateQuotaForIdentityCommand(identity.Address, metricKey, max, period); - - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.Find(identity.Address, A._, A._)).Returns(identity); - - var metricsRepository = new FindMetricsStubRepository(new Metric(MetricKey.NumberOfSentMessages, "Number Of Sent Messages")); - var handler = CreateHandler(identitiesRepository, metricsRepository); - - // Act - var response = await handler.Handle(command, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNullOrEmpty(); - response.Period.Should().Be(period); - response.Max.Should().Be(max); - response.Metric.Key.Should().Be(metricKey); - - A.CallTo(() => identitiesRepository.Update(A.That.Matches(t => - t.Address == identity.Address && - t.TierId == tierId && - t.IndividualQuotas.Count == 1) - , CancellationToken.None) - ).MustHaveHappened(); - } - - [Fact] - public void Create_quota_with_invalid_metric_key_throws_domain_exception() - { - // Arrange - var identity = new Identity(CreateRandomIdentityAddress(), TierId.Parse("TIRsomeTierId1111111")); - var command = new CreateQuotaForIdentityCommand(identity.Address, "An-Invalid-Metric-Key", 5, QuotaPeriod.Month); - var metricsRepository = new FindMetricsStubRepository(new Metric(MetricKey.NumberOfSentMessages, "Number Of Sent Messages")); - - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.Find(identity.Address, A._, A._)).Returns(identity); - - var handler = CreateHandler(identitiesRepository, metricsRepository); - - // Act - Func acting = async () => await handler.Handle(command, CancellationToken.None); - - // Assert - acting.Should().AwaitThrowAsync().Which.Code.Should().Be("error.platform.quotas.unsupportedMetricKey"); - } - - [Fact] - public void Create_quota_for_non_existent_identity_throws_not_found_exception() - { - // Arrange - var command = new CreateQuotaForIdentityCommand(IdentityAddress.Parse(CreateRandomIdentityAddress()), "An-Invalid-Metric-Key", 5, QuotaPeriod.Month); - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.Find(A._, A._, A._)).Returns((Identity?)null); - var metricsRepository = new FindMetricsStubRepository(new Metric(MetricKey.NumberOfSentMessages, "Number Of Sent Messages")); - var handler = CreateHandler(identitiesRepository, metricsRepository); - - // Act - Func acting = async () => await handler.Handle(command, CancellationToken.None); - - // Assert - var exception = acting.Should().AwaitThrowAsync().Which; - exception.Message.Should().StartWith("Identity"); - exception.Code.Should().Be("error.platform.recordNotFound"); - } - [Fact] public async Task Updates_metric_statuses_after_creating_quota_for_identity() { diff --git a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForTier/HandlerTests.cs b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForTier/HandlerTests.cs deleted file mode 100644 index 3c8f931bd6..0000000000 --- a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/CreateQuotaForTier/HandlerTests.cs +++ /dev/null @@ -1,63 +0,0 @@ -using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Quotas.Application.Tests.TestDoubles; -using Backbone.Modules.Quotas.Application.Tiers.Commands.CreateQuotaForTier; -using Backbone.Modules.Quotas.Domain.Aggregates.Identities; -using Backbone.Modules.Quotas.Domain.Aggregates.Metrics; -using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; -using Backbone.UnitTestTools.BaseClasses; -using FakeItEasy; -using FluentAssertions; -using FluentAssertions.Execution; -using Microsoft.Extensions.Logging; -using Xunit; -using MetricKey = Backbone.Modules.Quotas.Domain.Aggregates.Metrics.MetricKey; - -namespace Backbone.Modules.Quotas.Application.Tests.Tests.Quotas.CreateQuotaForTier; - -public class HandlerTests : AbstractTestsBase -{ - public HandlerTests() - { - AssertionScope.Current.FormattingOptions.MaxLines = 1000; - } - - [Fact] - public async Task Creates_quota_for_tier() - { - // Arrange - var tierId = TierId.Parse("TIRsomeTierId1111111"); - const int max = 5; - const QuotaPeriod period = QuotaPeriod.Month; - var metricKey = MetricKey.NumberOfSentMessages.Value; - var command = new CreateQuotaForTierCommand(tierId, metricKey, max, period); - var tier = new Tier(tierId, "some-tier-name"); - - var tierRepository = A.Fake(); - A.CallTo(() => tierRepository.Find(tierId, A._, A._)).Returns(tier); - - var metricsRepository = new FindMetricsStubRepository(new Metric(MetricKey.NumberOfSentMessages, "Number Of Sent Messages")); - var handler = CreateHandler(tierRepository, metricsRepository); - - // Act - var response = await handler.Handle(command, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNullOrEmpty(); - response.Period.Should().Be(period); - response.Max.Should().Be(max); - response.Metric.Key.Should().Be(metricKey); - - A.CallTo(() => tierRepository.Update(A.That.Matches(t => - t.Id == tierId && - t.Quotas.Count == 1) - , CancellationToken.None) - ).MustHaveHappened(); - } - - private Handler CreateHandler(ITiersRepository tiersRepository, FindMetricsStubRepository metricsRepository) - { - var logger = A.Fake>(); - - return new Handler(tiersRepository, logger, metricsRepository); - } -} diff --git a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteIndividualQuota/HandlerTests.cs b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteIndividualQuota/HandlerTests.cs deleted file mode 100644 index 38c520921f..0000000000 --- a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteIndividualQuota/HandlerTests.cs +++ /dev/null @@ -1,109 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Exceptions; -using Backbone.BuildingBlocks.Domain; -using Backbone.Modules.Quotas.Application.Identities.Commands.DeleteQuotaForIdentity; -using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Quotas.Domain.Aggregates.Identities; -using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Extensions; -using FakeItEasy; -using FluentAssertions; -using Microsoft.Extensions.Logging; -using Xunit; -using Handler = Backbone.Modules.Quotas.Application.Identities.Commands.DeleteQuotaForIdentity.Handler; -using MetricKey = Backbone.Modules.Quotas.Domain.Aggregates.Metrics.MetricKey; - -namespace Backbone.Modules.Quotas.Application.Tests.Tests.Quotas.DeleteIndividualQuota; -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Delete_individual_quota() - { - // Arrange - var identity = new Identity("some-identity-address", TierId.Parse("tier-id")); - var createdQuota = identity.CreateIndividualQuota(MetricKey.NumberOfSentMessages, 5, QuotaPeriod.Month); - var command = new DeleteQuotaForIdentityCommand(identity.Address, createdQuota.Id); - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.Find(identity.Address, A._, A._)).Returns(identity); - var handler = CreateHandler(identitiesRepository); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - A.CallTo(() => identitiesRepository.Update(A.That.Matches(t => - t.Address == identity.Address && - t.IndividualQuotas.Count == 0) - , CancellationToken.None) - ).MustHaveHappenedOnceExactly(); - } - - [Fact] - public async Task Deletes_individual_quota_for_identity_with_multiple_quotas() - { - // Arrange - var identity = new Identity("some-identity-address", TierId.Parse("tier-id")); - var quotaToDelete = identity.CreateIndividualQuota(MetricKey.NumberOfSentMessages, 1, QuotaPeriod.Day); - identity.CreateIndividualQuota(MetricKey.NumberOfSentMessages, 5, QuotaPeriod.Month); - identity.CreateIndividualQuota(MetricKey.NumberOfSentMessages, 50, QuotaPeriod.Year); - var command = new DeleteQuotaForIdentityCommand(identity.Address, quotaToDelete.Id); - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.Find(identity.Address, A._, A._)).Returns(identity); - var handler = CreateHandler(identitiesRepository); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - A.CallTo(() => identitiesRepository.Update(A.That.Matches(t => - t.Address == identity.Address && - t.IndividualQuotas.Count == 2) - , CancellationToken.None) - ).MustHaveHappenedOnceExactly(); - } - - [Fact] - public void Fails_to_delete_individual_quota_for_inexistent_identity() - { - // Arrange - var command = new DeleteQuotaForIdentityCommand("some-inexistent-identity", "QUOsomequotaid111111"); - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.Find("some-inexistent-identity", A._, A._))!.Returns(Task.FromResult(null!)); - var handler = CreateHandler(identitiesRepository); - - // Act - var acting = async () => await handler.Handle(command, CancellationToken.None); - - // Assert - var exception = acting.Should().AwaitThrowAsync().Which; - exception.Message.Should().StartWith("Identity"); - exception.Code.Should().Be("error.platform.recordNotFound"); - } - - [Fact] - public void Fails_to_delete_individual_quota_when_providing_an_inexistent_quota_id() - { - // Arrange - const string identityAddress = "some-identity-address"; - var identity = new Identity("some-identity-address", TierId.Parse("tier-id")); - var command = new DeleteQuotaForIdentityCommand(identityAddress, "QUOsomequotaid111111"); - var identitiesRepository = A.Fake(); - A.CallTo(() => identitiesRepository.Find(identityAddress, A._, A._)).Returns(identity); - var handler = CreateHandler(identitiesRepository); - - // Act - var acting = async () => await handler.Handle(command, CancellationToken.None); - - // Assert - var exception = acting.Should().AwaitThrowAsync().Which; - exception.Message.Should().StartWith("IndividualQuota"); - exception.Code.Should().Be("error.platform.recordNotFound"); - } - - private Handler CreateHandler(IIdentitiesRepository identitiesRepository) - { - var logger = A.Fake>(); - - return new Handler(identitiesRepository, logger); - } -} diff --git a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteTierQuotaDefinition/HandlerTests.cs b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteTierQuotaDefinition/HandlerTests.cs deleted file mode 100644 index e56a1f9e80..0000000000 --- a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Quotas/DeleteTierQuotaDefinition/HandlerTests.cs +++ /dev/null @@ -1,128 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Exceptions; -using Backbone.BuildingBlocks.Domain; -using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Quotas.Application.Tests.Extensions; -using Backbone.Modules.Quotas.Application.Tiers.Commands.DeleteTierQuotaDefinition; -using Backbone.Modules.Quotas.Domain.Aggregates.Identities; -using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; -using Backbone.UnitTestTools.BaseClasses; -using FakeItEasy; -using FluentAssertions; -using FluentAssertions.Execution; -using Microsoft.Extensions.Logging; -using Xunit; -using MetricKey = Backbone.Modules.Quotas.Domain.Aggregates.Metrics.MetricKey; - -namespace Backbone.Modules.Quotas.Application.Tests.Tests.Quotas.DeleteTierQuotaDefinition; - -public class HandlerTests : AbstractTestsBase -{ - public HandlerTests() - { - AssertionScope.Current.FormattingOptions.MaxLines = 1000; - } - - [Fact] - public async Task Deletes_tier_quota_definition() - { - // Arrange - var tierId = TierId.Parse("tier-id"); - var tier = new Tier(tierId, "some-tier-name"); - - tier.CreateQuota(MetricKey.NumberOfSentMessages, 5, QuotaPeriod.Month); - - var command = new DeleteTierQuotaDefinitionCommand(tier.Id, tier.Quotas.First().Id); - - var tiersRepository = A.Fake(); - A.CallTo(() => tiersRepository.Find(tierId, A._, A._)).Returns(tier); - - var handler = CreateHandler(tiersRepository); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - A.CallTo(() => tiersRepository.Update(A.That.Matches(t => - t.Id == tierId && - t.Quotas.Count == 0) - , CancellationToken.None) - ).MustHaveHappenedOnceExactly(); - } - - [Fact] - public async Task Deletes_tier_quota_definition_with_multiple_quotas() - { - // Arrange - var tierId = TierId.Parse("tier-id"); - var tier = new Tier(tierId, "some-tier-name"); - - tier.CreateQuota(MetricKey.NumberOfSentMessages, 5, QuotaPeriod.Month); - tier.CreateQuota(MetricKey.NumberOfSentMessages, 10, QuotaPeriod.Year); - tier.CreateQuota(MetricKey.NumberOfSentMessages, 15, QuotaPeriod.Total); - - var command = new DeleteTierQuotaDefinitionCommand(tier.Id, tier.Quotas.First().Id); - - var tiersRepository = A.Fake(); - A.CallTo(() => tiersRepository.Find(tierId, A._, A._)).Returns(tier); - - var handler = CreateHandler(tiersRepository); - - // Act - await handler.Handle(command, CancellationToken.None); - - // Assert - A.CallTo(() => tiersRepository.Update(A.That.Matches(t => - t.Id == tierId && - t.Quotas.Count == 2) - , CancellationToken.None) - ).MustHaveHappened(); - } - - [Fact] - public async Task Fails_to_delete_tier_quota_definition_for_missing_tier() - { - // Arrange - var tierId = TierId.Parse("tier-id"); - - var command = new DeleteTierQuotaDefinitionCommand(tierId, "SomeTierQuotaDefinitionId"); - - var tiersRepository = A.Fake(); - A.CallTo(() => tiersRepository.Find(tierId, A._, A._)).Returns(Task.FromResult(null)); - - var handler = CreateHandler(tiersRepository); - - // Act - var acting = async () => await handler.Handle(command, CancellationToken.None); - - // Assert - await acting.Should().ThrowAsync(); - } - - [Fact] - public async Task Fails_to_delete_tier_quota_definition_for_missing_quota() - { - // Arrange - var tierId = TierId.Parse("tier-id"); - var tier = new Tier(tierId, "some-tier-name"); - - var command = new DeleteTierQuotaDefinitionCommand(tier.Id, "SomeTierQuotaDefinitionId"); - - var tiersRepository = A.Fake(); - A.CallTo(() => tiersRepository.Find(tierId, A._, A._)).Returns(tier); - - var handler = CreateHandler(tiersRepository); - - // Act - var acting = async () => await handler.Handle(command, CancellationToken.None); - - // Assert - await acting.Should().ThrowAsync().WithErrorCode("error.platform.recordNotFound"); - } - - private Handler CreateHandler(ITiersRepository tiersRepository) - { - var logger = A.Fake>(); - - return new Handler(tiersRepository, logger); - } -} diff --git a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Tiers/GetTierById/HandlerTests.cs b/Modules/Quotas/test/Quotas.Application.Tests/Tests/Tiers/GetTierById/HandlerTests.cs deleted file mode 100644 index ad5615308a..0000000000 --- a/Modules/Quotas/test/Quotas.Application.Tests/Tests/Tiers/GetTierById/HandlerTests.cs +++ /dev/null @@ -1,93 +0,0 @@ -using Backbone.Modules.Quotas.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Quotas.Application.Tests.TestDoubles; -using Backbone.Modules.Quotas.Application.Tiers.Queries.GetTierById; -using Backbone.Modules.Quotas.Domain.Aggregates.Identities; -using Backbone.Modules.Quotas.Domain.Aggregates.Metrics; -using Backbone.Modules.Quotas.Domain.Aggregates.Tiers; -using Backbone.UnitTestTools.BaseClasses; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Quotas.Application.Tests.Tests.Tiers.GetTierById; -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Gets_tier_by_id_one_quota() - { - // Arrange - var tierId = TierId.Parse("tier-id"); - const string tierName = "some-tier-name"; - var tier = new Tier(tierId, tierName); - - var metricKey = MetricKey.NumberOfSentMessages; - const int max = 5; - const QuotaPeriod period = QuotaPeriod.Month; - tier.CreateQuota(metricKey, max, period); - - var stubTiersRepository = new FindTiersStubRepository(tier); - var stubMetricsRepository = new FindAllWithKeysMetricsStubRepository(new List { new(metricKey, "Number Of Sent Messages") }); - - var handler = CreateHandler(stubTiersRepository, stubMetricsRepository); - - // Act - var result = await handler.Handle(new GetTierByIdQuery(tierId), CancellationToken.None); - - // Assert - result.Id.Should().Be(tierId); - result.Name.Should().Be(tierName); - result.Quotas.Should().HaveCount(1); - - result.Quotas.First().Max.Should().Be(max); - result.Quotas.First().Period.Should().Be(period); - } - - [Fact] - public async Task Gets_tier_by_id_multiple_quotas() - { - // Arrange - var tierId = TierId.Parse("tier-id"); - const string tierName = "some-tier-name"; - var tier = new Tier(tierId, tierName); - - var metricWithTwoQuotas = new Metric(MetricKey.NumberOfSentMessages, "Number Of Sent Messages"); - var metricWithOneQuota = new Metric(MetricKey.UsedFileStorageSpace, "Used File Storage Space"); - var metrics = new List { metricWithTwoQuotas, metricWithOneQuota }; - - tier.CreateQuota(metricWithTwoQuotas.Key, 1, QuotaPeriod.Day); - tier.CreateQuota(metricWithOneQuota.Key, 1, QuotaPeriod.Day); - tier.CreateQuota(metricWithTwoQuotas.Key, 5, QuotaPeriod.Week); - - var stubTiersRepository = new FindTiersStubRepository(tier); - var stubMetricsRepository = new FindAllWithKeysMetricsStubRepository(metrics); - - var handler = CreateHandler(stubTiersRepository, stubMetricsRepository); - - // Act - var result = await handler.Handle(new GetTierByIdQuery(tierId), CancellationToken.None); - - // Assert - result.Id.Should().Be(tierId); - result.Name.Should().Be(tierName); - result.Quotas.Should().HaveCount(3); - - result.Quotas.ElementAt(0).Metric.Key.Should().Be(metricWithTwoQuotas.Key.Value); - result.Quotas.ElementAt(0).Metric.DisplayName.Should().Be(metricWithTwoQuotas.DisplayName); - result.Quotas.ElementAt(0).Max.Should().Be(1); - result.Quotas.ElementAt(0).Period.Should().Be(QuotaPeriod.Day); - - result.Quotas.ElementAt(1).Metric.Key.Should().Be(metricWithOneQuota.Key.Value); - result.Quotas.ElementAt(1).Metric.DisplayName.Should().Be(metricWithOneQuota.DisplayName); - result.Quotas.ElementAt(1).Max.Should().Be(1); - result.Quotas.ElementAt(1).Period.Should().Be(QuotaPeriod.Day); - - result.Quotas.ElementAt(2).Metric.Key.Should().Be(metricWithTwoQuotas.Key.Value); - result.Quotas.ElementAt(2).Metric.DisplayName.Should().Be(metricWithTwoQuotas.DisplayName); - result.Quotas.ElementAt(2).Max.Should().Be(5); - result.Quotas.ElementAt(2).Period.Should().Be(QuotaPeriod.Week); - } - - private Handler CreateHandler(ITiersRepository tiersRepository, IMetricsRepository metricsRepository) - { - return new Handler(tiersRepository, metricsRepository); - } -} diff --git a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/AcceptRelationship/Handler.Tests.cs b/Modules/Relationships/src/Relationships.Application/Relationships/Commands/AcceptRelationship/Handler.Tests.cs deleted file mode 100644 index c54fb0cca8..0000000000 --- a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/AcceptRelationship/Handler.Tests.cs +++ /dev/null @@ -1,81 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Relationships.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Relationships.Application.TestHelpers; -using Backbone.Modules.Relationships.Domain.Aggregates.Relationships; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Data; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Relationships.Application.Relationships.Commands.AcceptRelationship; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Returns_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var fakeRelationshipsRepository = A.Fake(); - var relationship = TestData.CreatePendingRelationship(to: activeIdentity); - A.CallTo(() => fakeRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeUserContext, fakeRelationshipsRepository); - - // Act - var response = await handler.Handle(new AcceptRelationshipCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNull(); - response.Status.Should().Be(RelationshipStatus.Active); - response.AuditLog.Should().HaveCount(2); - } - - [Fact] - public async Task Saves_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var mockRelationshipsRepository = A.Fake(); - var relationship = TestData.CreatePendingRelationship(to: activeIdentity); - A.CallTo(() => mockRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeUserContext, mockRelationshipsRepository); - - // Act - await handler.Handle(new AcceptRelationshipCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - A.CallTo( - () => mockRelationshipsRepository.Update( - A.That.Matches(r => r.Id == relationship.Id && r.Status == RelationshipStatus.Active)) - ) - .MustHaveHappenedOnceExactly(); - } - - private static Handler CreateHandler(IUserContext userContext, IRelationshipsRepository relationshipsRepository, IEventBus? eventBus = null) - { - eventBus ??= A.Fake(); - return new Handler(relationshipsRepository, userContext, eventBus); - } -} diff --git a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/AcceptRelationshipReactivation/Handler.Tests.cs b/Modules/Relationships/src/Relationships.Application/Relationships/Commands/AcceptRelationshipReactivation/Handler.Tests.cs deleted file mode 100644 index be5eca964c..0000000000 --- a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/AcceptRelationshipReactivation/Handler.Tests.cs +++ /dev/null @@ -1,83 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Relationships.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Relationships.Application.TestHelpers; -using Backbone.Modules.Relationships.Domain.Aggregates.Relationships; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Data; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Relationships.Application.Relationships.Commands.AcceptRelationshipReactivation; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Returns_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var identityTo = TestDataGenerator.CreateRandomIdentityAddress(); - - var fakeRelationshipsRepository = A.Fake(); - var relationship = TestData.CreateRelationshipWithRequestedReactivation(from: activeIdentity, to: identityTo, reactivationRequestedBy: identityTo); - A.CallTo(() => fakeRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeRelationshipsRepository, fakeUserContext); - - // Act - var response = await handler.Handle(new AcceptRelationshipReactivationCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNull(); - response.Status.Should().Be(RelationshipStatus.Active); - response.AuditLog.Should().HaveCount(5); - } - - [Fact] - public async Task Saves_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var identityTo = TestDataGenerator.CreateRandomIdentityAddress(); - - var mockRelationshipsRepository = A.Fake(); - var relationship = TestData.CreateRelationshipWithRequestedReactivation(from: activeIdentity, to: identityTo, reactivationRequestedBy: identityTo); - A.CallTo(() => mockRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(mockRelationshipsRepository, fakeUserContext); - - // Act - await handler.Handle(new AcceptRelationshipReactivationCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - A.CallTo( - () => mockRelationshipsRepository.Update( - A.That.Matches(r => r.Id == relationship.Id && r.Status == RelationshipStatus.Active)) - ) - .MustHaveHappenedOnceExactly(); - } - - private static Handler CreateHandler(IRelationshipsRepository relationshipsRepository, IUserContext userContext) - { - return new Handler(relationshipsRepository, userContext); - } -} diff --git a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/CreateRelationship/Handler.Tests.cs b/Modules/Relationships/src/Relationships.Application/Relationships/Commands/CreateRelationship/Handler.Tests.cs deleted file mode 100644 index 00631ad8c7..0000000000 --- a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/CreateRelationship/Handler.Tests.cs +++ /dev/null @@ -1,150 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Exceptions; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.DevelopmentKit.Identity.ValueObjects; -using Backbone.Modules.Relationships.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Relationships.Domain.Aggregates.Relationships; -using Backbone.Modules.Relationships.Domain.Aggregates.RelationshipTemplates; -using Backbone.Tooling; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Data; -using Backbone.UnitTestTools.Extensions; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Relationships.Application.Relationships.Commands.CreateRelationship; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Saves_the_created_relationship() - { - // Arrange - SystemTime.Set("2020-01-01"); - var activeIdentity = IdentityAddress.Create([0], "localhost"); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var fakeRelationshipTemplatesRepository = A.Fake(); - var relationshipTemplate = new RelationshipTemplate( - TestDataGenerator.CreateRandomIdentityAddress(), - TestDataGenerator.CreateRandomDeviceId(), - 1, - DateTime.Parse("2021-01-01"), - [] - ); - A.CallTo(() => fakeRelationshipTemplatesRepository.Find(relationshipTemplate.Id, activeIdentity, A._, A._)) - .Returns(relationshipTemplate); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var mockRelationshipsRepository = A.Fake(); - - var handler = CreateHandler(fakeRelationshipTemplatesRepository, fakeUserContext, mockRelationshipsRepository); - - // Act - await handler.Handle(new CreateRelationshipCommand - { - RelationshipTemplateId = relationshipTemplate.Id - }, CancellationToken.None); - - // Assert - A.CallTo(() => mockRelationshipsRepository.Add(A._, A._)).MustHaveHappenedOnceExactly(); - } - - [Fact] - public async Task Returns_data_of_created_relationship() - { - // Arrange - SystemTime.Set("2020-01-01"); - var activeIdentity = IdentityAddress.Create([0], "localhost"); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var fakeRelationshipTemplatesRepository = A.Fake(); - var relationshipTemplate = new RelationshipTemplate( - TestDataGenerator.CreateRandomIdentityAddress(), - TestDataGenerator.CreateRandomDeviceId(), - 1, - DateTime.Parse("2021-01-01"), - [] - ); - A.CallTo(() => fakeRelationshipTemplatesRepository.Find(relationshipTemplate.Id, activeIdentity, A._, A._)) - .Returns(relationshipTemplate); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeRelationshipTemplatesRepository, fakeUserContext); - - // Act - var response = await handler.Handle(new CreateRelationshipCommand - { - RelationshipTemplateId = relationshipTemplate.Id - }, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNull(); - response.RelationshipTemplateId.Should().Be(relationshipTemplate.Id); - response.From.Should().Be(activeIdentity); - response.To.Should().Be(relationshipTemplate.CreatedBy); - response.CreatedAt.Should().Be(SystemTime.UtcNow); - response.Status.Should().Be(RelationshipStatus.Pending); - response.AuditLog.Should().HaveCount(1); - } - - [Fact] - public void Throws_when_no_template_with_given_id_exists() - { - // Arrange - var relationshipTemplateId = RelationshipTemplateId.Parse("RLTNonExistingReltId"); - var address = IdentityAddress.Create([0], "localhost"); - - var relationshipTemplatesRepository = A.Fake(); - A.CallTo(() => relationshipTemplatesRepository.Find(relationshipTemplateId, address, A._, A._)) - .Returns(null); - - var handler = CreateHandler(relationshipTemplatesRepository); - - // Act - var acting = () => handler.Handle(new CreateRelationshipCommand - { - RelationshipTemplateId = relationshipTemplateId - }, CancellationToken.None); - - // Assert - acting.Should().AwaitThrowAsync().Which.Message.Should().Contain("RelationshipTemplate"); - } - - private static Handler CreateHandler(IRelationshipTemplatesRepository relationshipTemplatesRepository) - { - return CreateHandler(relationshipTemplatesRepository, null, null, null); - } - - private static Handler CreateHandler(IRelationshipTemplatesRepository relationshipTemplatesRepository, IUserContext userContext, IEventBus eventBus) - { - return CreateHandler(relationshipTemplatesRepository, userContext, eventBus, null); - } - - private static Handler CreateHandler(IRelationshipTemplatesRepository relationshipTemplatesRepository, IUserContext userContext) - { - return CreateHandler(relationshipTemplatesRepository, userContext, null, null); - } - - private static Handler CreateHandler(IRelationshipTemplatesRepository relationshipTemplatesRepository, IUserContext userContext, IRelationshipsRepository relationshipsRepository) - { - return CreateHandler(relationshipTemplatesRepository, userContext, null, relationshipsRepository); - } - - private static Handler CreateHandler(IRelationshipTemplatesRepository relationshipTemplatesRepository, IUserContext? userContext, IEventBus? eventBus, - IRelationshipsRepository? relationshipsRepository) - { - userContext ??= A.Dummy(); - relationshipsRepository ??= A.Dummy(); - - var handler = new Handler(userContext, relationshipsRepository, relationshipTemplatesRepository); - return handler; - } -} diff --git a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/DecomposeRelationship/Handler.Tests.cs b/Modules/Relationships/src/Relationships.Application/Relationships/Commands/DecomposeRelationship/Handler.Tests.cs deleted file mode 100644 index d193670c37..0000000000 --- a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/DecomposeRelationship/Handler.Tests.cs +++ /dev/null @@ -1,82 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Relationships.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Relationships.Application.TestHelpers; -using Backbone.Modules.Relationships.Domain.Aggregates.Relationships; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Data; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Relationships.Application.Relationships.Commands.DecomposeRelationship; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Returns_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var fakeRelationshipsRepository = A.Fake(); - var relationship = TestData.CreateTerminatedRelationship(activeIdentity); - A.CallTo(() => fakeRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeRelationshipsRepository, fakeUserContext); - - // Act - var response = await handler.Handle(new DecomposeRelationshipCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNull(); - response.Status.Should().Be(RelationshipStatus.DeletionProposed); - response.AuditLog.Should().HaveCount(4); - } - - [Fact] - public async Task Saves_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var mockRelationshipsRepository = A.Fake(); - var relationship = TestData.CreateTerminatedRelationship(from: activeIdentity); - A.CallTo(() => mockRelationshipsRepository - .FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(mockRelationshipsRepository, fakeUserContext); - - // Act - await handler.Handle(new DecomposeRelationshipCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - A.CallTo( - () => mockRelationshipsRepository.Update( - A.That.Matches(r => r.Id == relationship.Id && r.Status == RelationshipStatus.DeletionProposed)) - ) - .MustHaveHappenedOnceExactly(); - } - - private static Handler CreateHandler(IRelationshipsRepository relationshipsRepository, IUserContext userContext, IEventBus? eventBus = null) - { - eventBus ??= A.Dummy(); - return new Handler(relationshipsRepository, userContext, eventBus); - } -} diff --git a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RejectRelationship/Handler.Tests.cs b/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RejectRelationship/Handler.Tests.cs deleted file mode 100644 index 572de55238..0000000000 --- a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RejectRelationship/Handler.Tests.cs +++ /dev/null @@ -1,81 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Relationships.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Relationships.Application.TestHelpers; -using Backbone.Modules.Relationships.Domain.Aggregates.Relationships; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Data; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Relationships.Application.Relationships.Commands.RejectRelationship; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Returns_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var fakeRelationshipsRepository = A.Fake(); - var relationship = TestData.CreatePendingRelationship(to: activeIdentity); - A.CallTo(() => fakeRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeUserContext, fakeRelationshipsRepository); - - // Act - var response = await handler.Handle(new RejectRelationshipCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNull(); - response.Status.Should().Be(RelationshipStatus.Rejected); - response.AuditLog.Should().HaveCount(2); - } - - [Fact] - public async Task Saves_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var mockRelationshipsRepository = A.Fake(); - var relationship = TestData.CreatePendingRelationship(to: activeIdentity); - A.CallTo(() => mockRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeUserContext, mockRelationshipsRepository); - - // Act - await handler.Handle(new RejectRelationshipCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - A.CallTo( - () => mockRelationshipsRepository.Update( - A.That.Matches(r => r.Id == relationship.Id && r.Status == RelationshipStatus.Rejected)) - ) - .MustHaveHappenedOnceExactly(); - } - - private static Handler CreateHandler(IUserContext userContext, IRelationshipsRepository relationshipsRepository, IEventBus? eventBus = null) - { - eventBus ??= A.Fake(); - return new Handler(relationshipsRepository, userContext, eventBus); - } -} diff --git a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RejectRelationshipReactivation/Handler.Tests.cs b/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RejectRelationshipReactivation/Handler.Tests.cs deleted file mode 100644 index 4bbb2e83cb..0000000000 --- a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RejectRelationshipReactivation/Handler.Tests.cs +++ /dev/null @@ -1,84 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Relationships.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Relationships.Application.TestHelpers; -using Backbone.Modules.Relationships.Domain.Aggregates.Relationships; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Data; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Relationships.Application.Relationships.Commands.RejectRelationshipReactivation; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Happy_path() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var identityTo = TestDataGenerator.CreateRandomIdentityAddress(); - - var fakeRelationshipsRepository = A.Fake(); - var relationship = TestData.CreateRelationshipWithRequestedReactivation(from: activeIdentity, to: identityTo, reactivationRequestedBy: identityTo); - - A.CallTo(() => fakeRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeRelationshipsRepository, fakeUserContext); - - // Act - var response = await handler.Handle(new RejectRelationshipReactivationCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNull(); - response.Status.Should().Be(RelationshipStatus.Terminated); - response.AuditLog.Should().HaveCount(5); // AuditLog(Creation->Acceptance->Termination->Reactivation->Rejection) - } - - [Fact] - public async Task Saves_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var identityTo = TestDataGenerator.CreateRandomIdentityAddress(); - - var mockRelationshipsRepository = A.Fake(); - var relationship = TestData.CreateRelationshipWithRequestedReactivation(from: activeIdentity, to: identityTo, reactivationRequestedBy: identityTo); - A.CallTo(() => mockRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(mockRelationshipsRepository, fakeUserContext); - - // Act - await handler.Handle(new RejectRelationshipReactivationCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - A.CallTo( - () => mockRelationshipsRepository.Update( - A.That.Matches(r => r.Id == relationship.Id && r.Status == RelationshipStatus.Terminated)) - ) - .MustHaveHappenedOnceExactly(); - } - - private static Handler CreateHandler(IRelationshipsRepository relationshipsRepository, IUserContext userContext) - { - return new Handler(relationshipsRepository, userContext); - } -} diff --git a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RequestRelationshipReactivation/Handler.Tests.cs b/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RequestRelationshipReactivation/Handler.Tests.cs deleted file mode 100644 index 3b847ab72d..0000000000 --- a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RequestRelationshipReactivation/Handler.Tests.cs +++ /dev/null @@ -1,80 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Relationships.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Relationships.Application.TestHelpers; -using Backbone.Modules.Relationships.Domain.Aggregates.Relationships; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Data; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Relationships.Application.Relationships.Commands.RequestRelationshipReactivation; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Returns_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var fakeRelationshipsRepository = A.Fake(); - var relationship = TestData.CreateTerminatedRelationship(); - A.CallTo(() => fakeRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeUserContext, fakeRelationshipsRepository); - - // Act - var response = await handler.Handle(new RequestRelationshipReactivationCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNull(); - response.AuditLog.Should().HaveCount(4); - } - - [Fact] - public async Task Saves_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var mockRelationshipsRepository = A.Fake(); - var relationship = TestData.CreateTerminatedRelationship(); - A.CallTo(() => mockRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeUserContext, mockRelationshipsRepository); - - // Act - await handler.Handle(new RequestRelationshipReactivationCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - A.CallTo( - () => mockRelationshipsRepository.Update( - A.That.Matches(r => r.Id == relationship.Id)) - ) - .MustHaveHappenedOnceExactly(); - } - - private static Handler CreateHandler(IUserContext userContext, IRelationshipsRepository relationshipsRepository, IEventBus? eventBus = null) - { - eventBus ??= A.Fake(); - return new Handler(relationshipsRepository, userContext, eventBus); - } -} diff --git a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RevokeRelationship/Handler.Tests.cs b/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RevokeRelationship/Handler.Tests.cs deleted file mode 100644 index babee8715c..0000000000 --- a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RevokeRelationship/Handler.Tests.cs +++ /dev/null @@ -1,81 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Relationships.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Relationships.Application.TestHelpers; -using Backbone.Modules.Relationships.Domain.Aggregates.Relationships; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Data; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Relationships.Application.Relationships.Commands.RevokeRelationship; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Returns_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var fakeRelationshipsRepository = A.Fake(); - var relationship = TestData.CreatePendingRelationship(from: activeIdentity); - A.CallTo(() => fakeRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeUserContext, fakeRelationshipsRepository); - - // Act - var response = await handler.Handle(new RevokeRelationshipCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNull(); - response.Status.Should().Be(RelationshipStatus.Revoked); - response.AuditLog.Should().HaveCount(2); - } - - [Fact] - public async Task Saves_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var mockRelationshipsRepository = A.Fake(); - var relationship = TestData.CreatePendingRelationship(from: activeIdentity); - A.CallTo(() => mockRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeUserContext, mockRelationshipsRepository); - - // Act - await handler.Handle(new RevokeRelationshipCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - A.CallTo( - () => mockRelationshipsRepository.Update( - A.That.Matches(r => r.Id == relationship.Id && r.Status == RelationshipStatus.Revoked)) - ) - .MustHaveHappenedOnceExactly(); - } - - private static Handler CreateHandler(IUserContext userContext, IRelationshipsRepository relationshipsRepository, IEventBus? eventBus = null) - { - eventBus ??= A.Fake(); - return new Handler(relationshipsRepository, userContext, eventBus); - } -} diff --git a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RevokeRelationshipReactivation/Handler.Tests.cs b/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RevokeRelationshipReactivation/Handler.Tests.cs deleted file mode 100644 index 1d1943d799..0000000000 --- a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/RevokeRelationshipReactivation/Handler.Tests.cs +++ /dev/null @@ -1,77 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Relationships.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Relationships.Application.TestHelpers; -using Backbone.Modules.Relationships.Domain.Aggregates.Relationships; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Data; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Relationships.Application.Relationships.Commands.RevokeRelationshipReactivation; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Returns_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var relationship = TestData.CreateRelationshipWithRequestedReactivation(from: activeIdentity, to: TestDataGenerator.CreateRandomIdentityAddress(), reactivationRequestedBy: activeIdentity); - - var fakeRelationshipsRepository = A.Fake(); - A.CallTo(() => fakeRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(TestDataGenerator.CreateRandomDeviceId()); - - var handler = CreateHandler(fakeUserContext, fakeRelationshipsRepository); - - // Act - var response = await handler.Handle(new RevokeRelationshipReactivationCommand() - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNull(); - response.Status.Should().Be(RelationshipStatus.Terminated); - response.AuditLog.Should().HaveCount(5); - } - - [Fact] - public async Task Saves_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var relationship = TestData.CreateRelationshipWithRequestedReactivation(from: activeIdentity, to: TestDataGenerator.CreateRandomIdentityAddress(), reactivationRequestedBy: activeIdentity); - - var mockRelationshipsRepository = A.Fake(); - A.CallTo(() => mockRelationshipsRepository.FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(TestDataGenerator.CreateRandomDeviceId()); - - var handler = CreateHandler(fakeUserContext, mockRelationshipsRepository); - - // Act - await handler.Handle(new RevokeRelationshipReactivationCommand() - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - A.CallTo( - () => mockRelationshipsRepository.Update( - A.That.Matches(r => r.Id == relationship.Id && r.Status == RelationshipStatus.Terminated)) - ) - .MustHaveHappenedOnceExactly(); - } - - private static Handler CreateHandler(IUserContext userContext, IRelationshipsRepository relationshipsRepository) - { - return new Handler(relationshipsRepository, userContext); - } -} diff --git a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/TerminateRelationship/Handler.Tests.cs b/Modules/Relationships/src/Relationships.Application/Relationships/Commands/TerminateRelationship/Handler.Tests.cs deleted file mode 100644 index e33b4276b1..0000000000 --- a/Modules/Relationships/src/Relationships.Application/Relationships/Commands/TerminateRelationship/Handler.Tests.cs +++ /dev/null @@ -1,83 +0,0 @@ -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.EventBus; -using Backbone.BuildingBlocks.Application.Abstractions.Infrastructure.UserContext; -using Backbone.Modules.Relationships.Application.Infrastructure.Persistence.Repository; -using Backbone.Modules.Relationships.Application.TestHelpers; -using Backbone.Modules.Relationships.Domain.Aggregates.Relationships; -using Backbone.UnitTestTools.BaseClasses; -using Backbone.UnitTestTools.Data; -using FakeItEasy; -using FluentAssertions; -using Xunit; - -namespace Backbone.Modules.Relationships.Application.Relationships.Commands.TerminateRelationship; - -public class HandlerTests : AbstractTestsBase -{ - [Fact] - public async Task Returns_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var fakeRelationshipsRepository = A.Fake(); - var relationship = TestData.CreateActiveRelationship(from: activeIdentity); - A.CallTo(() => fakeRelationshipsRepository - .FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeUserContext, fakeRelationshipsRepository); - - // Act - var response = await handler.Handle(new TerminateRelationshipCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - response.Id.Should().NotBeNull(); - response.Status.Should().Be(RelationshipStatus.Terminated); - response.AuditLog.Should().HaveCount(3); - } - - [Fact] - public async Task Saves_the_updated_relationship() - { - // Arrange - var activeIdentity = TestDataGenerator.CreateRandomIdentityAddress(); - var activeDevice = TestDataGenerator.CreateRandomDeviceId(); - - var mockRelationshipsRepository = A.Fake(); - var relationship = TestData.CreateActiveRelationship(from: activeIdentity); - A.CallTo(() => mockRelationshipsRepository - .FindRelationship(relationship.Id, activeIdentity, A._, true)).Returns(relationship); - - var fakeUserContext = A.Fake(); - A.CallTo(() => fakeUserContext.GetAddress()).Returns(activeIdentity); - A.CallTo(() => fakeUserContext.GetDeviceId()).Returns(activeDevice); - - var handler = CreateHandler(fakeUserContext, mockRelationshipsRepository); - - // Act - await handler.Handle(new TerminateRelationshipCommand - { - RelationshipId = relationship.Id - }, CancellationToken.None); - - // Assert - A.CallTo( - () => mockRelationshipsRepository.Update( - A.That.Matches(r => r.Id == relationship.Id && r.Status == RelationshipStatus.Terminated)) - ) - .MustHaveHappenedOnceExactly(); - } - - private static Handler CreateHandler(IUserContext userContext, IRelationshipsRepository relationshipsRepository, IEventBus? eventBus = null) - { - eventBus ??= A.Fake(); - return new Handler(relationshipsRepository, userContext, eventBus); - } -} diff --git a/Sdks/AdminApi.Sdk/src/Client.cs b/Sdks/AdminApi.Sdk/src/Client.cs index 48e63098d5..c961e3a593 100644 --- a/Sdks/AdminApi.Sdk/src/Client.cs +++ b/Sdks/AdminApi.Sdk/src/Client.cs @@ -10,6 +10,7 @@ using Backbone.AdminApi.Sdk.Endpoints.Relationships; using Backbone.AdminApi.Sdk.Endpoints.Tiers; using Backbone.BuildingBlocks.SDK.Endpoints.Common; +using Backbone.Tooling.JsonConverters; namespace Backbone.AdminApi.Sdk; @@ -20,6 +21,7 @@ private Client(HttpClient httpClient, string apiKey) var authenticator = new XsrfAndApiKeyAuthenticator(apiKey, httpClient); var jsonSerializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; + jsonSerializerOptions.Converters.Add(new UrlSafeBase64ToByteArrayJsonConverter()); var endpointClient = new EndpointClient(httpClient, authenticator, jsonSerializerOptions);