diff --git a/docs/ValueProposition.md b/docs/ValueProposition.md index cd1fddb5..7f6b741b 100644 --- a/docs/ValueProposition.md +++ b/docs/ValueProposition.md @@ -58,11 +58,11 @@ This person will need to quickly understand the value proposition of SaaStack an They may encounter some objections, either design decisions or principles behind it, that they can't move past. * They will be guided by what they already know, so it will have to be a tech stack they know already. - * They may or may not trust examples of things they are not experienced with, and some may not adopt things they won't feel they have mastered yet. + * They may or may not trust examples of things they are not experienced with, and some may not adopt things they won't feel they have mastered yet. * They will be motivated by associating themselves with the latest and greatest in this technology stack (i.e. .NET). - * They may or may not be up to speed on those things. So they will see value in someone showing them the latest and greatest. + * They may or may not be up to speed on those things. So they will see value in someone showing them the latest and greatest. * They will be interested to learn more about the proposed architectural styles (e.g. Event Sourcing, Microservices, Clean Architecture, etc.). - * They may or may not be experienced in their uses either. And will be looking for evidence or opinions on why they should consider them for their context. + * They may or may not be experienced in their uses either. And will be looking for evidence or opinions on why they should consider them for their context. We believe that if the founding developer makes any kind of purchase or contribution to obtaining SaaStack, they are also going to have an expectation of having some support for adopting it, from some kind of community, where they can have questions answered and may provide feedback. @@ -85,12 +85,12 @@ We assume that: - A tech startup has identified some kind of *problem* in some kind of target *market*, and this target market will (in the future) be able to sustain the growth of the business. - They understand that there is some kind of *opportunity* out there that this problem that the market represents to them, and they accept that there is some kind of risk in competing to be a solution to that problem, that the market will choose over/with other options. - They may or may not have a concrete solution to this problem at this stage, but must have some ideas to validate in a segment of the market. - - We believe that many tech startups already believe that they have a winning solution in mind, and some have already convinced themselves that they only have to build the solution in their mind, and the market will come knocking on their doors, throwing money at them. + - We believe that many tech startups already believe that they have a winning solution in mind, and some have already convinced themselves that they only have to build the solution in their mind, and the market will come knocking on their doors, throwing money at them. - In any case, some software will need to be designed, built, and deployed somewhere in order to test, validate, measure, or even acquire buyers/users for their new product business. - "Making" this software is the primary job of the CTO and/or tech lead of a startup. - - We believe that nowadays, it is imperative to research, design, build, deploy measure, and learn incrementally and iteratively to discover what really works in a market segment. These people understand that. + - We believe that nowadays, it is imperative to research, design, build, deploy measure, and learn incrementally and iteratively to discover what really works in a market segment. These people understand that. - Those people have to start somewhere with making some software product/prototype, and it is usually starting from scratch. - - We believe that sometimes, it is more cost-effective to start with other low-tech solutions, low-tech tools, no-code solutions, or adapt readily available tools before a tech company accepts the risk and cost of investing in doing their own custom development. All these approaches are very viable approaches, and would likely precede the need for a solution like SaaStack. + - We believe that sometimes, it is more cost-effective to start with other low-tech solutions, low-tech tools, no-code solutions, or adapt readily available tools before a tech company accepts the risk and cost of investing in doing their own custom development. All these approaches are very viable approaches, and would likely precede the need for a solution like SaaStack. **Early Validation:** So, our first job here is the job of getting some validated results (from a market segment) by using something more economical than making a full-blown software product of their own from scratch. diff --git a/docs/design-principles/0010-rest-api.md b/docs/design-principles/0010-rest-api.md index e939a1cd..0931a318 100644 --- a/docs/design-principles/0010-rest-api.md +++ b/docs/design-principles/0010-rest-api.md @@ -332,10 +332,10 @@ These properties generally don't form part of the route. In the API the naming convention for search type API's has been the following: * For search type API's, where the request contains something to search for, (even in cases where only a single result is expected) we have been using the convention: `GET /resources/search`, and defining the search criteria in the QueryString. - * For example, to determine if a user exists for a specified email address, we have the SearchUsers API: `GET /users/search?email=bob@company.com`. + * For example, to determine if a user exists for a specified email address, we have the SearchUsers API: `GET /users/search?email=bob@company.com`. * For Listing type API's, where the request may not contain any search criteria, and usually returns different variants of a resource based upon the caller, or context, we have been using the convention: `GET /resources`, and defining any parameters in the QueryString also. - * For example, to list the car that you own, we have the ListForCallerCars API: `GET /cars`. + * For example, to list the car that you own, we have the ListForCallerCars API: `GET /cars`. The difference in the naming convention is purely for semantics. For search APIs, the route adds the `/search` part. @@ -628,26 +628,26 @@ We report errors as HTTP status codes `4XX` and `5XX`). These are the common HTTP status codes for errors: * `400 - BadRequest` (the request is incorrectly formatted) - * Validation failed - * A required input is missing or invalid at the time - * The request is not allowed at this time because the resource/context is not in a required state - (i.e. business rule violation). + * Validation failed + * A required input is missing or invalid at the time + * The request is not allowed at this time because the resource/context is not in a required state - (i.e. business rule violation). * `401 - NotAuthorized` (the user has not authenticated when authentication is required) - * No access_token provided for a secure call - * The access_token expired or is invalid + * No access_token provided for a secure call + * The access_token expired or is invalid * `402 - PaymentRequired` (the user is using a feature that has not been paid for) - * The caller is using a feature associated to a subscription plan that the user does not have + * The caller is using a feature associated to a subscription plan that the user does not have * `403 - Forbidden` (the user may be authenticated, but they are not authorized to this specific resource at this time) - * The caller is not in the required role - * [May decide to throw 404 instead to obscure reason from hacker] + * The caller is not in the required role + * [May decide to throw 404 instead to obscure reason from hacker] * `404 - NotFound` (a resource does not exist) - * The resource does not exist - * [May decide to throw 404 instead of a 403 if the caller is not allowed access to this resource to obscure the resource rather than admit it exists but the authenticated user does not have access to it] + * The resource does not exist + * [May decide to throw 404 instead of a 403 if the caller is not allowed access to this resource to obscure the resource rather than admit it exists but the authenticated user does not have access to it] * `405 - MethodNotAllowed` (Verb/API cannot be called at this time) - * i.e. It is invalid to call it for this resource at this time. - * i.e. It no longer exists for this resource at this time, or it never existed for this resource (not implemented yet). + * i.e. It is invalid to call it for this resource at this time. + * i.e. It no longer exists for this resource at this time, or it never existed for this resource (not implemented yet). * `409 - Conflict` (conflict with the current state of the target resource) - * Resource already exists + * Resource already exists * `500 - InternalServerError` (something bad happened in our code that we did not expect, and did not handle in the code) - * Unhandled/Unexpected exception (not covered above) + * Unhandled/Unexpected exception (not covered above) > HTTP Status codes are explained in detail here: [HTTP Status Codes](http://en.wikipedia.org/wiki/Http_error_codes) diff --git a/src/ApiHost1/Apis/TestingOnly/ValidationsValidatedTestingOnlyRequestValidator.cs b/src/ApiHost1/Apis/TestingOnly/ValidationsValidatedTestingOnlyRequestValidator.cs index 403169fe..d4d81216 100644 --- a/src/ApiHost1/Apis/TestingOnly/ValidationsValidatedTestingOnlyRequestValidator.cs +++ b/src/ApiHost1/Apis/TestingOnly/ValidationsValidatedTestingOnlyRequestValidator.cs @@ -10,10 +10,16 @@ public class ValidationsValidatedTestingOnlyRequestValidator : AbstractValidator { public ValidationsValidatedTestingOnlyRequestValidator() { - RuleFor(req => req.Id).NotEmpty().WithMessage(Resources.GetTestingOnlyValidatedRequestValidator_InvalidId); - RuleFor(req => req.Field1).NotEmpty().Matches(@"[\d]{1,3}") + RuleFor(req => req.Id) + .NotEmpty() + .WithMessage(Resources.GetTestingOnlyValidatedRequestValidator_InvalidId); + RuleFor(req => req.Field1) + .NotEmpty() + .Matches(@"[\d]{1,3}") .WithMessage(Resources.GetTestingOnlyValidatedRequestValidator_InvalidField1); - RuleFor(req => req.Field2).NotEmpty().Matches(@"[\d]{1,3}") + RuleFor(req => req.Field2) + .NotEmpty() + .Matches(@"[\d]{1,3}") .WithMessage(Resources.GetTestingOnlyValidatedRequestValidator_InvalidField2); } } diff --git a/src/ApiHost1/Program.cs b/src/ApiHost1/Program.cs index a36201df..467da74c 100644 --- a/src/ApiHost1/Program.cs +++ b/src/ApiHost1/Program.cs @@ -9,7 +9,6 @@ .ConfigureApiHost(modules, RecorderOptions.BackEndApiHost); app.Run(); - namespace ApiHost1 { [UsedImplicitly] diff --git a/src/ApiHost1/Properties/launchSettings.json b/src/ApiHost1/Properties/launchSettings.json index 332775ca..c0aa1481 100644 --- a/src/ApiHost1/Properties/launchSettings.json +++ b/src/ApiHost1/Properties/launchSettings.json @@ -27,7 +27,7 @@ "ASPNETCORE_ENVIRONMENT": "Production" } }, - "SourceGenerator-Development": { + "ApiHandler-SourceGenerator-Development": { "commandName": "DebugRoslynComponent", "targetProject": "../ApiHost1/ApiHost1.csproj" } diff --git a/src/Application.Common/Caller.cs b/src/Application.Common/Caller.cs index 76c79384..1f9630ee 100644 --- a/src/Application.Common/Caller.cs +++ b/src/Application.Common/Caller.cs @@ -172,9 +172,7 @@ public ExternalWebHookAccountCaller(string? callId = null) { CallId = callId ?? GenerateCallId(); Roles = new ICallerContext.CallerRoles(new[] { UserRoles.ServiceAccount }, null); - FeatureSets = - new ICallerContext.CallerFeatureSets( - new[] { UserFeatureSets.Core }, null); + FeatureSets = new ICallerContext.CallerFeatureSets(new[] { UserFeatureSets.Core }, null); } public ICallerContext.CallerRoles Roles { get; } diff --git a/src/Application.Interfaces.UnitTests/GetOptionsExtensionsSpec.cs b/src/Application.Interfaces.UnitTests/GetOptionsExtensionsSpec.cs index a881ba15..aa809ea1 100644 --- a/src/Application.Interfaces.UnitTests/GetOptionsExtensionsSpec.cs +++ b/src/Application.Interfaces.UnitTests/GetOptionsExtensionsSpec.cs @@ -12,54 +12,59 @@ public void WhenShouldExpandEmbeddedResourceAndNullOptions_ThenReturnsTrue() { var result = ((GetOptions)null!).ShouldExpandEmbeddedResource(x => x.AProperty1); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenShouldExpandEmbeddedResourceAndExpandIsAll_ThenReturnsTrue() { - var result = new GetOptions(ExpandOptions.All) - .ShouldExpandEmbeddedResource(x => x.AProperty1); + var result = new GetOptions(ExpandOptions.All).ShouldExpandEmbeddedResource(x => x.AProperty1); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenShouldExpandEmbeddedResourceAndExpandIsNone_ThenReturnsFalse() { - var result = new GetOptions(ExpandOptions.None) - .ShouldExpandEmbeddedResource(x => x.AProperty1); + var result = new GetOptions(ExpandOptions.None).ShouldExpandEmbeddedResource(x => x.AProperty1); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenShouldExpandEmbeddedResourceAndExpandIsCustomAndNoChildResources_ThenReturnsFalse() { - var result = new GetOptions(ExpandOptions.Custom, new List()) - .ShouldExpandEmbeddedResource(x => x.AProperty1); + var result = + new GetOptions(ExpandOptions.Custom, new List()).ShouldExpandEmbeddedResource(x => + x.AProperty1); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenShouldExpandEmbeddedResourceAndExpandIsCustomAndUnknownChildResources_ThenReturnsFalse() { - var result = new GetOptions(ExpandOptions.Custom, - new List { "TestResource.AnotherProperty" }) - .ShouldExpandEmbeddedResource(x => x.AProperty1); + var result = + new GetOptions(ExpandOptions.Custom, new List { "TestResource.AnotherProperty" }) + .ShouldExpandEmbeddedResource(x => x.AProperty1); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenShouldExpandEmbeddedResourceAndExpandIsCustomAndKnownChildResources_ThenReturnsTrue() { - var result = new GetOptions(ExpandOptions.Custom, - new List { "TestResource.AProperty1" }) - .ShouldExpandEmbeddedResource(x => x.AProperty1); + var result = + new GetOptions(ExpandOptions.Custom, new List { "TestResource.AProperty1" }) + .ShouldExpandEmbeddedResource(x => x.AProperty1); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } } diff --git a/src/Application.Interfaces.UnitTests/SearchOptionsExtensionsSpec.cs b/src/Application.Interfaces.UnitTests/SearchOptionsExtensionsSpec.cs index ebaf8add..61feb60a 100644 --- a/src/Application.Interfaces.UnitTests/SearchOptionsExtensionsSpec.cs +++ b/src/Application.Interfaces.UnitTests/SearchOptionsExtensionsSpec.cs @@ -11,7 +11,8 @@ public void WhenToMetadataSafeWithNullSearchOptions_ThenReturnsDefaultSearchMeta { var results = ((SearchOptions)null!).ToMetadata(); - results.Total.Should().Be(0); + results.Total.Should() + .Be(0); } [Fact] @@ -19,7 +20,8 @@ public void WhenToMetadataSafeWithNullSearchOptionsAndTotal_ThenReturnsDefaultSe { var results = ((SearchOptions)null!).ToMetadata(11); - results.Total.Should().Be(11); + results.Total.Should() + .Be(11); } [Fact] @@ -29,7 +31,8 @@ public void WhenToMetadataSafeWithInitialSearchOptions_ThenReturnsSearchMetadata var results = searchOptions.ToMetadata(); - results.Total.Should().Be(0); + results.Total.Should() + .Be(0); } [Fact] @@ -45,13 +48,21 @@ public void WhenToMetadataSafe_ThenReturnsPopulatedSearchMetadata() var results = searchOptions.ToMetadata(); - results.Total.Should().Be(0); - results.Sort!.Direction.Should().Be(SortDirection.Descending); - results.Sort.By.Should().Be("asortfield"); - results.Offset.Should().Be(9); - results.Limit.Should().Be(6); - results.Filter!.Fields.Count.Should().Be(1); - results.Filter.Fields[0].Should().Be("afilterfield"); + results.Total.Should() + .Be(0); + results.Sort!.Direction.Should() + .Be(SortDirection.Descending); + results.Sort.By.Should() + .Be("asortfield"); + results.Offset.Should() + .Be(9); + results.Limit.Should() + .Be(6); + results.Filter!.Fields.Count.Should() + .Be(1); + results.Filter.Fields[0] + .Should() + .Be("afilterfield"); } [Fact] @@ -67,12 +78,20 @@ public void WhenToMetadataSafeAndTotal_ThenReturnsPopulatedSearchMetadata() var results = searchOptions.ToMetadata(11); - results.Total.Should().Be(11); - results.Sort!.Direction.Should().Be(SortDirection.Descending); - results.Sort.By.Should().Be("asortfield"); - results.Offset.Should().Be(9); - results.Limit.Should().Be(6); - results.Filter!.Fields.Count.Should().Be(1); - results.Filter.Fields[0].Should().Be("afilterfield"); + results.Total.Should() + .Be(11); + results.Sort!.Direction.Should() + .Be(SortDirection.Descending); + results.Sort.By.Should() + .Be("asortfield"); + results.Offset.Should() + .Be(9); + results.Limit.Should() + .Be(6); + results.Filter!.Fields.Count.Should() + .Be(1); + results.Filter.Fields[0] + .Should() + .Be("afilterfield"); } } \ No newline at end of file diff --git a/src/Application.Interfaces.UnitTests/SearchOptionsSpec.cs b/src/Application.Interfaces.UnitTests/SearchOptionsSpec.cs index 36acec0b..653aee42 100644 --- a/src/Application.Interfaces.UnitTests/SearchOptionsSpec.cs +++ b/src/Application.Interfaces.UnitTests/SearchOptionsSpec.cs @@ -13,68 +13,88 @@ public class SearchOptionsSpec public void WhenApplyWithMetadataAndNoLimit_ThenTakesDefaultLimit() { _searchOptions.Limit = SearchOptions.NoLimit; - var queried = Enumerable.Range(1, SearchOptions.MaxLimit + 1).ToList(); + var queried = Enumerable.Range(1, SearchOptions.MaxLimit + 1) + .ToList(); var result = _searchOptions.ApplyWithMetadata(queried); - result.Results.Count.Should().Be(SearchOptions.DefaultLimit); - result.Metadata.Filter!.Fields.Any().Should().BeFalse(); - result.Metadata.Sort!.Should().BeNull(); - result.Metadata.Offset.Should().Be(SearchOptions.NoOffset); - result.Metadata.Limit.Should().Be(SearchOptions.NoLimit); - result.Metadata.Total.Should().Be(SearchOptions.MaxLimit + 1); + result.Results.Count.Should() + .Be(SearchOptions.DefaultLimit); + result.Metadata.Filter!.Fields.Any() + .Should() + .BeFalse(); + result.Metadata.Sort!.Should() + .BeNull(); + result.Metadata.Offset.Should() + .Be(SearchOptions.NoOffset); + result.Metadata.Limit.Should() + .Be(SearchOptions.NoLimit); + result.Metadata.Total.Should() + .Be(SearchOptions.MaxLimit + 1); } [Fact] public void WhenApplyWithMetadataAndLimitLessThanMax_ThenTakesLimit() { _searchOptions.Limit = SearchOptions.MaxLimit - 1; - var queried = Enumerable.Range(1, SearchOptions.MaxLimit + 1).ToList(); + var queried = Enumerable.Range(1, SearchOptions.MaxLimit + 1) + .ToList(); var result = _searchOptions.ApplyWithMetadata(queried); - result.Results.Count.Should().Be(SearchOptions.MaxLimit - 1); + result.Results.Count.Should() + .Be(SearchOptions.MaxLimit - 1); AssertSearchResults(result); - result.Metadata.Total.Should().Be(SearchOptions.MaxLimit + 1); + result.Metadata.Total.Should() + .Be(SearchOptions.MaxLimit + 1); } [Fact] public void WhenApplyWithMetadataAndLimitGreaterThanMax_ThenTakesMaxLimit() { _searchOptions.Limit = SearchOptions.MaxLimit + 1; - var queried = Enumerable.Range(1, SearchOptions.MaxLimit + 1).ToList(); + var queried = Enumerable.Range(1, SearchOptions.MaxLimit + 1) + .ToList(); var result = _searchOptions.ApplyWithMetadata(queried); - result.Results.Count.Should().Be(SearchOptions.MaxLimit); + result.Results.Count.Should() + .Be(SearchOptions.MaxLimit); AssertSearchResults(result); - result.Metadata.Total.Should().Be(SearchOptions.MaxLimit + 1); + result.Metadata.Total.Should() + .Be(SearchOptions.MaxLimit + 1); } [Fact] public void WhenApplyWithMetadataAndLimitLessThanMaxAndQueriedLessThanLimit_ThenTakesMaxQueried() { _searchOptions.Limit = SearchOptions.MaxLimit - 1; - var queried = Enumerable.Range(1, 66).ToList(); + var queried = Enumerable.Range(1, 66) + .ToList(); var result = _searchOptions.ApplyWithMetadata(queried); - result.Results.Count.Should().Be(66); + result.Results.Count.Should() + .Be(66); AssertSearchResults(result); - result.Metadata.Total.Should().Be(66); + result.Metadata.Total.Should() + .Be(66); } [Fact] public void WhenApplyWithMetadataAndLimitGreaterThanMaxAndQueriedLessThanLimit_ThenTakesMaxQueried() { _searchOptions.Limit = SearchOptions.MaxLimit + 1; - var queried = Enumerable.Range(1, 66).ToList(); + var queried = Enumerable.Range(1, 66) + .ToList(); var result = _searchOptions.ApplyWithMetadata(queried); - result.Results.Count.Should().Be(66); + result.Results.Count.Should() + .Be(66); AssertSearchResults(result); - result.Metadata.Total.Should().Be(66); + result.Metadata.Total.Should() + .Be(66); } [Fact] @@ -91,12 +111,20 @@ public void WhenApplyWithMetadataAndNoSorting_ThenNoOrdering() var result = _searchOptions.ApplyWithMetadata(queried); var results = result.Results.ToList(); - results.Count.Should().Be(3); - results[0].Should().Be(1); - results[1].Should().Be(6); - results[2].Should().Be(3); + results.Count.Should() + .Be(3); + results[0] + .Should() + .Be(1); + results[1] + .Should() + .Be(6); + results[2] + .Should() + .Be(3); AssertSearchResults(result); - result.Metadata.Total.Should().Be(3); + result.Metadata.Total.Should() + .Be(3); } [Fact] @@ -113,12 +141,20 @@ public void WhenApplyWithMetadataAndSortByIsEmpty_ThenNoOrdering() var result = _searchOptions.ApplyWithMetadata(queried); var results = result.Results.ToList(); - results.Count.Should().Be(3); - results[0].Should().Be(1); - results[1].Should().Be(6); - results[2].Should().Be(3); + results.Count.Should() + .Be(3); + results[0] + .Should() + .Be(1); + results[1] + .Should() + .Be(6); + results[2] + .Should() + .Be(3); AssertSearchResults(result); - result.Metadata.Total.Should().Be(3); + result.Metadata.Total.Should() + .Be(3); } [Fact] @@ -135,12 +171,20 @@ public void WhenApplyWithMetadataAndSortByIsUnknown_ThenNoOrdering() var result = _searchOptions.ApplyWithMetadata(queried); var results = result.Results.ToList(); - results.Count.Should().Be(3); - results[0].Should().Be(1); - results[1].Should().Be(6); - results[2].Should().Be(3); + results.Count.Should() + .Be(3); + results[0] + .Should() + .Be(1); + results[1] + .Should() + .Be(6); + results[2] + .Should() + .Be(3); AssertSearchResults(result); - result.Metadata.Total.Should().Be(3); + result.Metadata.Total.Should() + .Be(3); } [Fact] @@ -157,12 +201,20 @@ public void WhenApplyWithMetadataAndSortDirectionDescending_ThenOrderingByDefaul var result = _searchOptions.ApplyWithMetadata(queried); var results = result.Results.ToList(); - results.Count.Should().Be(3); - results[0].AProperty.Should().Be(1); - results[1].AProperty.Should().Be(3); - results[2].AProperty.Should().Be(6); + results.Count.Should() + .Be(3); + results[0] + .AProperty.Should() + .Be(1); + results[1] + .AProperty.Should() + .Be(3); + results[2] + .AProperty.Should() + .Be(6); AssertSearchResults(result); - result.Metadata.Total.Should().Be(3); + result.Metadata.Total.Should() + .Be(3); } [Fact] @@ -179,12 +231,20 @@ public void WhenApplyWithMetadataAndSortDirectionAscending_ThenOrderingAscending var result = _searchOptions.ApplyWithMetadata(queried); var results = result.Results.ToList(); - results.Count.Should().Be(3); - results[0].AProperty.Should().Be(1); - results[1].AProperty.Should().Be(3); - results[2].AProperty.Should().Be(6); + results.Count.Should() + .Be(3); + results[0] + .AProperty.Should() + .Be(1); + results[1] + .AProperty.Should() + .Be(3); + results[2] + .AProperty.Should() + .Be(6); AssertSearchResults(result); - result.Metadata.Total.Should().Be(3); + result.Metadata.Total.Should() + .Be(3); } [Fact] @@ -201,29 +261,43 @@ public void WhenApplyWithMetadataAndSortDirectionDescending_ThenOrderingDescendi var result = _searchOptions.ApplyWithMetadata(queried); var results = result.Results.ToList(); - results.Count.Should().Be(3); - results[0].AProperty.Should().Be(6); - results[1].AProperty.Should().Be(3); - results[2].AProperty.Should().Be(1); + results.Count.Should() + .Be(3); + results[0] + .AProperty.Should() + .Be(6); + results[1] + .AProperty.Should() + .Be(3); + results[2] + .AProperty.Should() + .Be(1); AssertSearchResults(result); - result.Metadata.Total.Should().Be(3); + result.Metadata.Total.Should() + .Be(3); } private void AssertSearchResults(SearchResults result) { - result.Metadata.Filter!.Fields.Should().BeSameAs(_searchOptions.Filter.Fields); + result.Metadata.Filter!.Fields.Should() + .BeSameAs(_searchOptions.Filter.Fields); if (_searchOptions.Sort.HasValue) { - result.Metadata.Sort!.By.Should().Be(_searchOptions.Sort.Value.By); - result.Metadata.Sort.Direction.Should().Be(_searchOptions.Sort.Value.Direction); + result.Metadata.Sort!.By.Should() + .Be(_searchOptions.Sort.Value.By); + result.Metadata.Sort.Direction.Should() + .Be(_searchOptions.Sort.Value.Direction); } else { - result.Metadata.Sort.Should().BeNull(); + result.Metadata.Sort.Should() + .BeNull(); } - result.Metadata.Offset.Should().Be(_searchOptions.Offset); - result.Metadata.Limit.Should().Be(_searchOptions.Limit); + result.Metadata.Offset.Should() + .Be(_searchOptions.Offset); + result.Metadata.Limit.Should() + .Be(_searchOptions.Limit); } } diff --git a/src/Application.Interfaces/GetOptions.cs b/src/Application.Interfaces/GetOptions.cs index ec4c289d..64dd7b46 100644 --- a/src/Application.Interfaces/GetOptions.cs +++ b/src/Application.Interfaces/GetOptions.cs @@ -13,8 +13,7 @@ public class GetOptions public static readonly GetOptions None = new(ExpandOptions.None, new List()); private readonly List _resourceReferences; - public GetOptions() - : this(ExpandOptions.All) + public GetOptions() : this(ExpandOptions.All) { } @@ -23,7 +22,8 @@ public GetOptions(ExpandOptions expand, List? childReferences = null, Ex Initial = @default ?? ExpandOptions.All; Expand = expand; _resourceReferences = childReferences.Exists() - ? childReferences!.Where(cr => cr.HasValue()).ToList() + ? childReferences!.Where(cr => cr.HasValue()) + .ToList() : new List(); } diff --git a/src/Application.Interfaces/ICallerContext.cs b/src/Application.Interfaces/ICallerContext.cs index 3f900f3e..cf13897a 100644 --- a/src/Application.Interfaces/ICallerContext.cs +++ b/src/Application.Interfaces/ICallerContext.cs @@ -45,7 +45,6 @@ public interface ICallerContext /// string? TenantId { get; } - /// /// Defines the authorization roles that a caller can have /// @@ -62,7 +61,8 @@ public CallerRoles(string[]? user, string[]? organisation) { User = user ?? Array.Empty(); Organisation = organisation ?? Array.Empty(); - All = User.Concat(Organisation).ToArray(); + All = User.Concat(Organisation) + .ToArray(); } public string[] All { get; } @@ -88,7 +88,8 @@ public CallerFeatureSets(string[]? user, string[]? organisation) { User = user ?? Array.Empty(); Organisation = organisation ?? Array.Empty(); - All = User.Concat(Organisation).ToArray(); + All = User.Concat(Organisation) + .ToArray(); } public string[] All { get; } diff --git a/src/Application.Interfaces/SearchOptionExtensions.cs b/src/Application.Interfaces/SearchOptionExtensions.cs index d947d95e..617953c4 100644 --- a/src/Application.Interfaces/SearchOptionExtensions.cs +++ b/src/Application.Interfaces/SearchOptionExtensions.cs @@ -9,7 +9,9 @@ public static class SearchOptionExtensions /// public static SearchResultMetadata ToMetadata(this SearchOptions? options, int total = 0) { - return Map(options.NotExists() ? new SearchOptions() : options!, total); + return Map(options.NotExists() + ? new SearchOptions() + : options!, total); static SearchResultMetadata Map(SearchOptions options, int total) { diff --git a/src/Application.Interfaces/SearchOptions.cs b/src/Application.Interfaces/SearchOptions.cs index ba8be1fd..b83f44ac 100644 --- a/src/Application.Interfaces/SearchOptions.cs +++ b/src/Application.Interfaces/SearchOptions.cs @@ -75,7 +75,8 @@ private SearchResults ApplyWithMetadata(IEnumerable r if (Sort.HasValue) { - unsorted = orderByFunc(unsorted, Sort.Value).ToList(); + unsorted = orderByFunc(unsorted, Sort.Value) + .ToList(); } IEnumerable unPaged = unsorted.ToArray(); @@ -132,8 +133,7 @@ internal static class SearchOptions var itemsToSort = items.ToArray(); try { - return itemsToSort - .AsQueryable() + return itemsToSort.AsQueryable() .OrderBy(expression); } catch (ParseException) diff --git a/src/CarsApi.IntegrationTests/CarsApiSpec.cs b/src/CarsApi.IntegrationTests/CarsApiSpec.cs index 5fb3e2f7..383220d3 100644 --- a/src/CarsApi.IntegrationTests/CarsApiSpec.cs +++ b/src/CarsApi.IntegrationTests/CarsApiSpec.cs @@ -29,11 +29,16 @@ public async Task WhenRegisterCar_ThenReturnsCar() var location = result.Headers.Location?.ToString(); - location.Should().StartWith("/cars/car_"); - result.Content.Car!.Id.Should().NotBeEmpty(); - result.Content.Car.Make.Should().Be("amake"); - result.Content.Car.Model.Should().Be("amodel"); - result.Content.Car.Year.Should().Be(2023); + location.Should() + .StartWith("/cars/car_"); + result.Content.Car!.Id.Should() + .NotBeEmpty(); + result.Content.Car.Make.Should() + .Be("amake"); + result.Content.Car.Model.Should() + .Be("amodel"); + result.Content.Car.Year.Should() + .Be(2023); } [Fact] @@ -48,7 +53,8 @@ public async Task WhenGetCar_ThenReturnsCar() var result = (await Api.GetAsync($"/cars/{car.Id}")).Content.Car!; - result.Id.Should().Be(car.Id); + result.Id.Should() + .Be(car.Id); } [Fact] @@ -63,8 +69,11 @@ public async Task WhenSearchAllCars_ThenReturnsCars() var result = (await Api.GetAsync("/cars")).Content.Cars!; - result.Count.Should().Be(1); - result[0].Id.Should().Be(car.Id); + result.Count.Should() + .Be(1); + result[0] + .Id.Should() + .Be(car.Id); } [Fact] @@ -84,7 +93,8 @@ public async Task WhenTakeCarOffline_ThenReturnsCar() EndAtUtc = DateTime.UtcNow.AddHours(2) })).Content.Car!; - result.Id.Should().Be(car.Id); + result.Id.Should() + .Be(car.Id); } [Fact] @@ -99,6 +109,7 @@ public async Task WhenDeleteCar_ThenDeletes() var result = await Api.DeleteAsync($"/cars/{car.Id}"); - result.StatusCode.Should().Be(HttpStatusCode.NoContent); + result.StatusCode.Should() + .Be(HttpStatusCode.NoContent); } } \ No newline at end of file diff --git a/src/CarsApi.UnitTests/Apis/Cars/DeleteCarRequestValidatorSpec.cs b/src/CarsApi.UnitTests/Apis/Cars/DeleteCarRequestValidatorSpec.cs index 5bdf03ce..7c9a046d 100644 --- a/src/CarsApi.UnitTests/Apis/Cars/DeleteCarRequestValidatorSpec.cs +++ b/src/CarsApi.UnitTests/Apis/Cars/DeleteCarRequestValidatorSpec.cs @@ -17,7 +17,8 @@ public class DeleteCarRequestValidatorSpec public DeleteCarRequestValidatorSpec() { var idFactory = new Mock(); - idFactory.Setup(idf => idf.IsValid(It.IsAny())).Returns(true); + idFactory.Setup(idf => idf.IsValid(It.IsAny())) + .Returns(true); _validator = new DeleteCarRequestValidator(idFactory.Object); _dto = new DeleteCarRequest { diff --git a/src/CarsApi.UnitTests/Apis/Cars/RegisterCarRequestValidatorSpec.cs b/src/CarsApi.UnitTests/Apis/Cars/RegisterCarRequestValidatorSpec.cs index aa2d1dec..e31a3b7e 100644 --- a/src/CarsApi.UnitTests/Apis/Cars/RegisterCarRequestValidatorSpec.cs +++ b/src/CarsApi.UnitTests/Apis/Cars/RegisterCarRequestValidatorSpec.cs @@ -36,7 +36,9 @@ public void WhenMakeIsNull_ThenThrows() { _dto.Make = null!; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.RegisterCarRequestValidator_InvalidMake); } @@ -45,7 +47,9 @@ public void WhenModelIsNull_ThenThrows() { _dto.Model = null!; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.RegisterCarRequestValidator_InvalidModel); } @@ -54,7 +58,9 @@ public void WhenYearIsLessThanMin_ThenThrows() { _dto.Year = Validations.Car.Year.Min - 1; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.RegisterCarRequestValidator_InvalidYear); } @@ -63,7 +69,9 @@ public void WhenYearIsMoreThanMax_ThenThrows() { _dto.Year = Validations.Car.Year.Max + 1; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.RegisterCarRequestValidator_InvalidYear); } } \ No newline at end of file diff --git a/src/CarsApi.UnitTests/Apis/Cars/TakeOfflineCarRequestValidatorSpec.cs b/src/CarsApi.UnitTests/Apis/Cars/TakeOfflineCarRequestValidatorSpec.cs index 1e83d854..39871858 100644 --- a/src/CarsApi.UnitTests/Apis/Cars/TakeOfflineCarRequestValidatorSpec.cs +++ b/src/CarsApi.UnitTests/Apis/Cars/TakeOfflineCarRequestValidatorSpec.cs @@ -19,7 +19,8 @@ public class TakeOfflineCarRequestValidatorSpec public TakeOfflineCarRequestValidatorSpec() { var idFactory = new Mock(); - idFactory.Setup(idf => idf.IsValid(It.IsAny())).Returns(true); + idFactory.Setup(idf => idf.IsValid(It.IsAny())) + .Returns(true); _validator = new TakeOfflineCarRequestValidator(idFactory.Object); _dto = new TakeOfflineCarRequest { @@ -40,7 +41,9 @@ public void WhenReasonIsInvalid_ThenThrows() { _dto.Reason = "aninvalidareason^"; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.TakeOfflineCarRequestValidator_InvalidReason); } @@ -49,7 +52,9 @@ public void WhenStartAtUtcIsPast_ThenThrows() { _dto.StartAtUtc = DateTime.UtcNow.Subtract(TimeSpan.FromHours(1)); - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.TakeOfflineCarRequestValidator_InvalidStartAtUtc); } @@ -58,7 +63,9 @@ public void WhenEndAtUtcIsPast_ThenThrows() { _dto.EndAtUtc = DateTime.UtcNow.Subtract(TimeSpan.FromHours(1)); - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.TakeOfflineCarRequestValidator_InvalidEndAtUtc); } @@ -68,7 +75,9 @@ public void WhenEndAtUtcIsLessThanStartAtUtc_ThenThrows() _dto.StartAtUtc = DateTime.UtcNow.Add(TimeSpan.FromHours(2)); _dto.EndAtUtc = DateTime.UtcNow.Add(TimeSpan.FromHours(1)); - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.TakeOfflineCarRequestValidator_InvalidEndAtUtc); } } \ No newline at end of file diff --git a/src/CarsApi/Apis/Cars/DeleteCarRequestValidator.cs b/src/CarsApi/Apis/Cars/DeleteCarRequestValidator.cs index f25bca23..ac63bb38 100644 --- a/src/CarsApi/Apis/Cars/DeleteCarRequestValidator.cs +++ b/src/CarsApi/Apis/Cars/DeleteCarRequestValidator.cs @@ -12,6 +12,8 @@ public class DeleteCarRequestValidator : AbstractValidator { public DeleteCarRequestValidator(IIdentifierFactory idFactory) { - RuleFor(req => req.Id).IsEntityId(idFactory).WithMessage(CommonValidationResources.AnyValidator_InvalidId); + RuleFor(req => req.Id) + .IsEntityId(idFactory) + .WithMessage(CommonValidationResources.AnyValidator_InvalidId); } } \ No newline at end of file diff --git a/src/CarsApi/Apis/Cars/RegisterCarRequestValidator.cs b/src/CarsApi/Apis/Cars/RegisterCarRequestValidator.cs index d08f9ece..c863268c 100644 --- a/src/CarsApi/Apis/Cars/RegisterCarRequestValidator.cs +++ b/src/CarsApi/Apis/Cars/RegisterCarRequestValidator.cs @@ -11,11 +11,14 @@ public class RegisterCarRequestValidator : AbstractValidator { public RegisterCarRequestValidator() { - RuleFor(req => req.Make).Matches(Validations.Car.Make) + RuleFor(req => req.Make) + .Matches(Validations.Car.Make) .WithMessage(ValidationResources.RegisterCarRequestValidator_InvalidMake); - RuleFor(req => req.Model).Matches(Validations.Car.Model) + RuleFor(req => req.Model) + .Matches(Validations.Car.Model) .WithMessage(ValidationResources.RegisterCarRequestValidator_InvalidModel); - RuleFor(req => req.Year).InclusiveBetween(Validations.Car.Year.Min, Validations.Car.Year.Max) + RuleFor(req => req.Year) + .InclusiveBetween(Validations.Car.Year.Min, Validations.Car.Year.Max) .WithMessage(ValidationResources.RegisterCarRequestValidator_InvalidYear); } } \ No newline at end of file diff --git a/src/CarsApi/Apis/Cars/TakeOfflineCarRequestValidator.cs b/src/CarsApi/Apis/Cars/TakeOfflineCarRequestValidator.cs index 8f63c293..7b48bbcb 100644 --- a/src/CarsApi/Apis/Cars/TakeOfflineCarRequestValidator.cs +++ b/src/CarsApi/Apis/Cars/TakeOfflineCarRequestValidator.cs @@ -14,12 +14,18 @@ public class TakeOfflineCarRequestValidator : AbstractValidator req.Id).IsEntityId(idFactory).WithMessage(CommonValidationResources.AnyValidator_InvalidId); - RuleFor(req => req.Reason).Matches(Validations.Car.Reason).When(req => req.Reason.HasValue()) + RuleFor(req => req.Id) + .IsEntityId(idFactory) + .WithMessage(CommonValidationResources.AnyValidator_InvalidId); + RuleFor(req => req.Reason) + .Matches(Validations.Car.Reason) + .When(req => req.Reason.HasValue()) .WithMessage(ValidationResources.TakeOfflineCarRequestValidator_InvalidReason); - RuleFor(req => req.StartAtUtc).GreaterThan(DateTime.UtcNow) + RuleFor(req => req.StartAtUtc) + .GreaterThan(DateTime.UtcNow) .WithMessage(ValidationResources.TakeOfflineCarRequestValidator_InvalidStartAtUtc); - RuleFor(req => req.EndAtUtc).GreaterThan(req => req.StartAtUtc) + RuleFor(req => req.EndAtUtc) + .GreaterThan(req => req.StartAtUtc) .WithMessage(ValidationResources.TakeOfflineCarRequestValidator_InvalidEndAtUtc); } } \ No newline at end of file diff --git a/src/CarsInfrastructure/Persistence/CarRepository.cs b/src/CarsInfrastructure/Persistence/CarRepository.cs index 3bdadcdc..3c712e52 100644 --- a/src/CarsInfrastructure/Persistence/CarRepository.cs +++ b/src/CarsInfrastructure/Persistence/CarRepository.cs @@ -44,7 +44,8 @@ public async Task, Error>> SearchAllCarsAsync(SearchOp { await Task.CompletedTask; - return new Result, Error>((IReadOnlyList)Cars.Select(car => car.ToCar()).ToList()); + return new Result, Error>((IReadOnlyList)Cars.Select(car => car.ToCar()) + .ToList()); } public async Task> Save(CarRoot car) diff --git a/src/Common.UnitTests/Common.UnitTests.csproj b/src/Common.UnitTests/Common.UnitTests.csproj index 931e4f9c..d172e6bf 100644 --- a/src/Common.UnitTests/Common.UnitTests.csproj +++ b/src/Common.UnitTests/Common.UnitTests.csproj @@ -2,6 +2,7 @@ net7.0 + true diff --git a/src/Common.UnitTests/Extensions/CollectionExtensionsSpec.cs b/src/Common.UnitTests/Extensions/CollectionExtensionsSpec.cs index 8abe5819..ba820817 100644 --- a/src/Common.UnitTests/Extensions/CollectionExtensionsSpec.cs +++ b/src/Common.UnitTests/Extensions/CollectionExtensionsSpec.cs @@ -12,32 +12,33 @@ public void WhenContainsIgnoreCaseAndEmptyCollection_ThenReturnsFalse() { var result = new List().ContainsIgnoreCase("avalue"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenContainsIgnoreCaseAndNoMatches_ThenReturnsFalse() { var result = new List - { - "avalue1", - "avalue2" - } - .ContainsIgnoreCase("anothervalue"); + { + "avalue1", + "avalue2" + }.ContainsIgnoreCase("anothervalue"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenContainsIgnoreCaseAndMatches_ThenReturnsTrue() { var result = new List - { - "avalue1", - "avalue2" - } - .ContainsIgnoreCase("avalue1"); + { + "avalue1", + "avalue2" + }.ContainsIgnoreCase("avalue1"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } } \ No newline at end of file diff --git a/src/Common.UnitTests/Extensions/DateTimeExtensionsSpec.cs b/src/Common.UnitTests/Extensions/DateTimeExtensionsSpec.cs index 846edc8f..ef4b6b81 100644 --- a/src/Common.UnitTests/Extensions/DateTimeExtensionsSpec.cs +++ b/src/Common.UnitTests/Extensions/DateTimeExtensionsSpec.cs @@ -12,7 +12,8 @@ public void WhenToIso8601WithNull_ThenReturnsEmpty() { var result = ((DateTime?)null).ToIso8601(); - result.Should().BeEmpty(); + result.Should() + .BeEmpty(); } [Fact] @@ -25,7 +26,8 @@ public void WhenToIso8601WithLocalTime_ThenReturnsUtcTime() var offset = TimeZoneInfo.Local.GetUtcOffset(time); var offsetTime = time.Subtract(offset); - result.Should().Be($"2023-09-{offsetTime.Day:D2}T{offsetTime.Hour:D2}:{offsetTime.Minute:D2}:00.0000000Z"); + result.Should() + .Be($"2023-09-{offsetTime.Day:D2}T{offsetTime.Hour:D2}:{offsetTime.Minute:D2}:00.0000000Z"); } [Fact] @@ -35,7 +37,8 @@ public void WhenToIso8601WithUniversalTime_ThenReturnsUtcTime() var result = time.ToIso8601(); - result.Should().Be("2023-09-24T12:00:00.0000000Z"); + result.Should() + .Be("2023-09-24T12:00:00.0000000Z"); } [Fact] @@ -43,7 +46,8 @@ public void WhenToUnixSecondsWithNull_ThenReturnsZero() { var result = ((DateTime?)null).ToUnixSeconds(); - result.Should().Be(0); + result.Should() + .Be(0); } [Fact] @@ -55,9 +59,11 @@ public void WhenToUnixSecondsWithLocalTime_ThenReturnsUtcTime() var offset = TimeZoneInfo.Local.GetUtcOffset(time); var offsetTime = time.Subtract(offset); - var expected = (long)offsetTime.Subtract(DateTime.UnixEpoch).TotalSeconds; + var expected = (long)offsetTime.Subtract(DateTime.UnixEpoch) + .TotalSeconds; - result.Should().Be(expected); + result.Should() + .Be(expected); } [Fact] @@ -67,7 +73,8 @@ public void WhenToUnixSecondsWithUniversalTime_ThenReturnsUtcTime() var result = time.ToUnixSeconds(); - result.Should().Be(1695556800L); + result.Should() + .Be(1695556800L); } [Fact] @@ -75,7 +82,8 @@ public void WhenToUnixMilliSecondsWithNull_ThenReturnsZero() { var result = ((DateTime?)null).ToUnixMilliSeconds(); - result.Should().Be(0); + result.Should() + .Be(0); } [Fact] @@ -87,9 +95,11 @@ public void WhenToUnixMilliSecondsWithLocalTime_ThenReturnsUtcTime() var offset = TimeZoneInfo.Local.GetUtcOffset(time); var offsetTime = time.Subtract(offset); - var expected = (long)offsetTime.Subtract(DateTime.UnixEpoch).TotalMilliseconds; + var expected = (long)offsetTime.Subtract(DateTime.UnixEpoch) + .TotalMilliseconds; - result.Should().Be(expected); + result.Should() + .Be(expected); } [Fact] @@ -99,7 +109,8 @@ public void WhenToUnixMilliSecondsWithUniversalTime_ThenReturnsUtcTime() var result = time.ToUnixMilliSeconds(); - result.Should().Be(1695556800000L); + result.Should() + .Be(1695556800000L); } [Fact] @@ -107,7 +118,8 @@ public void WhenFromIso8601AndNullValue_ThenReturnsMinDate() { var result = ((string?)null).FromIso8601(); - result.Should().Be(DateTime.MinValue); + result.Should() + .Be(DateTime.MinValue); } [Fact] @@ -115,7 +127,8 @@ public void WhenFromIso8601AndEmptyValue_ThenReturnsMinDate() { var result = string.Empty.FromIso8601(); - result.Should().Be(DateTime.MinValue); + result.Should() + .Be(DateTime.MinValue); } [Fact] @@ -123,15 +136,18 @@ public void WhenFromIso8601AndNotISO8601_ThenReturnsMinDate() { var result = "notadate".FromIso8601(); - result.Should().Be(DateTime.MinValue); + result.Should() + .Be(DateTime.MinValue); } [Fact] public void WhenFromIso8601AndOtherFormat_ThenReturnsMinDate() { - var result = DateTime.UtcNow.ToString("D").FromIso8601(); + var result = DateTime.UtcNow.ToString("D") + .FromIso8601(); - result.Should().Be(DateTime.MinValue); + result.Should() + .Be(DateTime.MinValue); } [Fact] @@ -140,16 +156,19 @@ public void WhenFromIso8601AndISO8601UtcWithNoMilliseconds_ThenReturnsUtcDate() var result = "2023-09-25T12:00:00Z".FromIso8601(); var expected = new DateTime(2023, 09, 25, 12, 0, 0, DateTimeKind.Utc); - result.Should().Be(expected); + result.Should() + .Be(expected); } [Fact] public void WhenFromIso8601AndISO8601UtcWithMillionths_ThenReturnsUtcDate() { var now = DateTime.UtcNow; - var result = now.ToIso8601().FromIso8601(); + var result = now.ToIso8601() + .FromIso8601(); - result.Should().Be(now); + result.Should() + .Be(now); } [Fact] @@ -158,7 +177,8 @@ public void WhenFromIso8601AndISO8601Local_ThenReturnsUtcDate() var result = "2023-09-25T12:00:00+13:00".FromIso8601(); var expected = new DateTime(2023, 09, 24, 23, 0, 0, DateTimeKind.Utc); - result.Should().Be(expected); + result.Should() + .Be(expected); } [Fact] @@ -166,7 +186,8 @@ public void WhenFromUnixTimestampWithNull_ThenReturnsMinDate() { var result = ((long?)null!).FromUnixTimestamp(); - result.Should().Be(DateTime.MinValue); + result.Should() + .Be(DateTime.MinValue); } [Fact] @@ -174,18 +195,21 @@ public void WhenFromUnixTimestampWithZero_ThenReturnsUnixEpoch() { var result = 0L.FromUnixTimestamp(); - result.Should().Be(DateTime.UnixEpoch); + result.Should() + .Be(DateTime.UnixEpoch); } [Fact] public void WhenFromUnixTimestampWithPastDateInSeconds_ThenReturnsDate() { - var hundredYearsAgo = DateTime.UtcNow.ToNearestSecond().Subtract(TimeSpan.FromDays(365 * 100)); + var hundredYearsAgo = DateTime.UtcNow.ToNearestSecond() + .Subtract(TimeSpan.FromDays(365 * 100)); var hundredYearsAgoUnixSeconds = hundredYearsAgo.ToUnixSeconds(); var result = hundredYearsAgoUnixSeconds.FromUnixTimestamp(); - result.Should().Be(hundredYearsAgo); + result.Should() + .Be(hundredYearsAgo); } [Fact] @@ -196,17 +220,20 @@ public void WhenFromUnixTimestampWithNowInSeconds_ThenReturnsDate() var result = nowUnixSeconds.FromUnixTimestamp(); - result.Should().Be(now); + result.Should() + .Be(now); } [Fact] public void WhenFromUnixTimestampWithFutureDateInSeconds_ThenReturnsDate() { - var tenYearsAFromNow = DateTime.UtcNow.ToNearestSecond().Add(TimeSpan.FromDays(365 * 10)); + var tenYearsAFromNow = DateTime.UtcNow.ToNearestSecond() + .Add(TimeSpan.FromDays(365 * 10)); var tenYearsFromNowUnixSeconds = tenYearsAFromNow.ToUnixSeconds(); var result = tenYearsFromNowUnixSeconds.FromUnixTimestamp(); - result.Should().Be(tenYearsAFromNow); + result.Should() + .Be(tenYearsAFromNow); } } \ No newline at end of file diff --git a/src/Common.UnitTests/Extensions/DictionaryExtensionsSpec.cs b/src/Common.UnitTests/Extensions/DictionaryExtensionsSpec.cs index e70d6af4..0cf5feed 100644 --- a/src/Common.UnitTests/Extensions/DictionaryExtensionsSpec.cs +++ b/src/Common.UnitTests/Extensions/DictionaryExtensionsSpec.cs @@ -14,7 +14,8 @@ public void WhenMergeAndSourceAndOtherIsEmpty_ThenContainsNothing() source.Merge(new Dictionary()); - source.Count.Should().Be(0); + source.Count.Should() + .Be(0); } [Fact] @@ -27,8 +28,10 @@ public void WhenMergeAndOtherIsEmpty_ThenNothingAdded() source.Merge(new Dictionary()); - source.Count.Should().Be(1); - source.Should().OnlyContain(pair => pair.Key == "aname"); + source.Count.Should() + .Be(1); + source.Should() + .OnlyContain(pair => pair.Key == "aname"); } [Fact] @@ -41,8 +44,10 @@ public void WhenMergeAndSourceIsEmpty_ThenOtherAdded() { "aname", "avalue" } }); - source.Count.Should().Be(1); - source.Should().OnlyContain(pair => pair.Key == "aname"); + source.Count.Should() + .Be(1); + source.Should() + .OnlyContain(pair => pair.Key == "aname"); } [Fact] @@ -58,9 +63,12 @@ public void WhenMergeAndSourceAndOtherHaveUniqueKeys_ThenOtherAdded() { "aname2", "avalue2" } }); - source.Count.Should().Be(2); - source.Should().Contain(pair => pair.Key == "aname1"); - source.Should().Contain(pair => pair.Key == "aname2"); + source.Count.Should() + .Be(2); + source.Should() + .Contain(pair => pair.Key == "aname1"); + source.Should() + .Contain(pair => pair.Key == "aname2"); } [Fact] @@ -78,9 +86,13 @@ public void WhenMergeAndSourceAndOtherHaveSameKeys_ThenSourceRemains() { "aname3", "avalue3" } }); - source.Count.Should().Be(3); - source.Should().Contain(pair => pair.Key == "aname1"); - source.Should().Contain(pair => pair.Key == "aname2"); - source.Should().Contain(pair => pair.Key == "aname3"); + source.Count.Should() + .Be(3); + source.Should() + .Contain(pair => pair.Key == "aname1"); + source.Should() + .Contain(pair => pair.Key == "aname2"); + source.Should() + .Contain(pair => pair.Key == "aname3"); } } \ No newline at end of file diff --git a/src/Common.UnitTests/Extensions/EnumExtensionsSpec.cs b/src/Common.UnitTests/Extensions/EnumExtensionsSpec.cs index e84914ff..4aeb117c 100644 --- a/src/Common.UnitTests/Extensions/EnumExtensionsSpec.cs +++ b/src/Common.UnitTests/Extensions/EnumExtensionsSpec.cs @@ -10,25 +10,27 @@ public class EnumExtensionsSpec [Fact] public void WhenToEnumAndEmpty_ThenThrows() { - "" - .Invoking(x => x.ToEnum()) - .Should().Throw(); + "".Invoking(x => x.ToEnum()) + .Should() + .Throw(); } [Fact] public void WhenToEnumAndNotMatches_ThenThrows() { - "notavalue" - .Invoking(x => x.ToEnum()) - .Should().Throw(); + "notavalue".Invoking(x => x.ToEnum()) + .Should() + .Throw(); } [Fact] public void WhenToEnumAndMatches_ThenReturnsMatched() { - var result = SourceEnum.OptionOne.ToString().ToEnum(); + var result = SourceEnum.OptionOne.ToString() + .ToEnum(); - result.Should().Be(SourceEnum.OptionOne); + result.Should() + .Be(SourceEnum.OptionOne); } [Fact] @@ -36,7 +38,8 @@ public void WhenToEnumOrDefaultAndEmpty_ThenReturnsDefault() { var result = "".ToEnumOrDefault(SourceEnum.OptionTwo); - result.Should().Be(SourceEnum.OptionTwo); + result.Should() + .Be(SourceEnum.OptionTwo); } [Fact] @@ -44,32 +47,35 @@ public void WhenToEnumOrDefaultAndNotMatches_ThenReturnsDefault() { var result = "notavalue".ToEnumOrDefault(SourceEnum.OptionTwo); - result.Should().Be(SourceEnum.OptionTwo); + result.Should() + .Be(SourceEnum.OptionTwo); } [Fact] public void WhenToEnumOrDefaultAndMatches_ThenReturnsMatched() { - var result = SourceEnum.OptionOne.ToString().ToEnumOrDefault(SourceEnum.OptionTwo); + var result = SourceEnum.OptionOne.ToString() + .ToEnumOrDefault(SourceEnum.OptionTwo); - result.Should().Be(SourceEnum.OptionOne); + result.Should() + .Be(SourceEnum.OptionOne); } - [Fact] public void WhenToEnumAndHasSameOption_ThenReturnsOption() { var result = SourceEnum.OptionTwo.ToEnum(); - result.Should().Be(TargetEnum.OptionTwo); + result.Should() + .Be(TargetEnum.OptionTwo); } [Fact] public void WhenToEnumAndMissingOptionInTarget_ThenThrows() { - SourceEnum.OptionOne - .Invoking(x => x.ToEnum()) - .Should().Throw() + SourceEnum.OptionOne.Invoking(x => x.ToEnum()) + .Should() + .Throw() .WithMessage($"Requested value '{SourceEnum.OptionOne}' was not found."); } @@ -78,7 +84,8 @@ public void WhenToEnumOrDefaultAndSameOption_ThenReturnsOption() { var result = SourceEnum.OptionTwo.ToEnumOrDefault(TargetEnum.OptionThree); - result.Should().Be(TargetEnum.OptionTwo); + result.Should() + .Be(TargetEnum.OptionTwo); } [Fact] @@ -86,7 +93,8 @@ public void WhenToEnumOrDefaultAndOptionNotExistsInTarget_ThenReturnsDefault() { var result = SourceEnum.OptionOne.ToEnumOrDefault(TargetEnum.OptionThree); - result.Should().Be(TargetEnum.OptionThree); + result.Should() + .Be(TargetEnum.OptionThree); } } diff --git a/src/Common.UnitTests/Extensions/StringExtensionsSpec.cs b/src/Common.UnitTests/Extensions/StringExtensionsSpec.cs index 81275a47..f72e8b62 100644 --- a/src/Common.UnitTests/Extensions/StringExtensionsSpec.cs +++ b/src/Common.UnitTests/Extensions/StringExtensionsSpec.cs @@ -12,7 +12,8 @@ public void WhenHasValueAndNull_ThenReturnsFalse() { var result = ((string?)null).HasValue(); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -20,7 +21,8 @@ public void WhenHasValueAndEmpty_ThenReturnsFalse() { var result = string.Empty.HasValue(); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -28,7 +30,8 @@ public void WhenHasValueAndOnlyWhitespace_ThenReturnsFalse() { var result = " ".HasValue(); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -36,7 +39,8 @@ public void WhenHasValueAndHasValue_ThenReturnsTrue() { var result = "avalue".HasValue(); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -44,7 +48,8 @@ public void WhenToJsonAndNull_ThenReturnsNull() { var result = ((string)null!).ToJson(); - result.Should().BeNull(); + result.Should() + .BeNull(); } [Fact] @@ -57,12 +62,13 @@ public void WhenToJsonAndDefaults_ThenReturnsJsonPrettyPrintedWithNoNullsInPasca Property3 = "" }.ToJson(); - result.Should().Be(""" - { - "Property1": "avalue", - "Property3": "" - } - """); + result.Should() + .Be(""" + { + "Property1": "avalue", + "Property3": "" + } + """); } [Fact] @@ -75,12 +81,13 @@ public void WhenToJsonAndCamelCase_ThenReturnsJsonPrettyPrintedWithNoNullsInCame Property3 = "" }.ToJson(casing: StringExtensions.JsonCasing.Camel); - result.Should().Be(""" - { - "property1": "avalue", - "property3": "" - } - """); + result.Should() + .Be(""" + { + "property1": "avalue", + "property3": "" + } + """); } [Fact] @@ -93,7 +100,8 @@ public void WhenToJsonAndNotPretty_ThenReturnsJsonWithNoNullsInPascal() Property3 = "" }.ToJson(false); - result.Should().Be("{\"Property1\":\"avalue\",\"Property3\":\"\"}"); + result.Should() + .Be("{\"Property1\":\"avalue\",\"Property3\":\"\"}"); } [Fact] @@ -106,13 +114,14 @@ public void WhenToJsonAndIncludeNulls_ThenReturnsJsonPrettyPrintedWithNullsInPas Property3 = "" }.ToJson(includeNulls: true); - result.Should().Be(""" - { - "Property1": "avalue", - "Property2": null, - "Property3": "" - } - """); + result.Should() + .Be(""" + { + "Property1": "avalue", + "Property2": null, + "Property3": "" + } + """); } [Fact] @@ -120,7 +129,8 @@ public void WhenIsMatchWithNull_ThenReturnsFalse() { var result = ((string)null!).IsMatchWith("apattern"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -128,7 +138,8 @@ public void WhenIsMatchWithEmpty_ThenReturnsFalse() { var result = string.Empty.IsMatchWith("apattern"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -136,7 +147,8 @@ public void WhenIsMatchWithNullPattern_ThenReturnsFalse() { var result = "avalue".IsMatchWith(null!); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -144,7 +156,8 @@ public void WhenIsMatchWithEmptyAndEmptyPattern_ThenReturnsTrue() { var result = string.Empty.IsMatchWith(string.Empty); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -152,7 +165,8 @@ public void WhenIsMatchAndNotMatches_ThenReturnsFalse() { var result = "avalue".IsMatchWith("anothervalue"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -160,7 +174,8 @@ public void WhenIsMatchAndMatches_ThenReturnsTrue() { var result = "avalue".IsMatchWith("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -168,7 +183,8 @@ public void WhenReplaceWithNull_ThenReturnsNull() { var result = ((string)null!).ReplaceWith("apattern", "areplacement"); - result.Should().BeNull(); + result.Should() + .BeNull(); } [Fact] @@ -176,7 +192,8 @@ public void WhenReplaceWithEmpty_ThenReturnsEmpty() { var result = string.Empty.ReplaceWith("apattern", "areplacement"); - result.Should().BeEmpty(); + result.Should() + .BeEmpty(); } [Fact] @@ -184,7 +201,8 @@ public void WhenReplaceWithNullPattern_ThenReturnsInput() { var result = "avalue".ReplaceWith(null!, "areplacement"); - result.Should().Be("avalue"); + result.Should() + .Be("avalue"); } [Fact] @@ -192,7 +210,8 @@ public void WhenReplaceWithEmptyAndEmptyPattern_ThenReturnsInput() { var result = "avalue".ReplaceWith(string.Empty, "areplacement"); - result.Should().Be("avalue"); + result.Should() + .Be("avalue"); } [Fact] @@ -200,7 +219,8 @@ public void WhenReplaceWithNoMatches_ThenReturnsInput() { var result = "avalue".ReplaceWith("apattern", "areplacement"); - result.Should().Be("avalue"); + result.Should() + .Be("avalue"); } [Fact] @@ -208,7 +228,8 @@ public void WhenReplaceWithMatches_ThenReturnsReplaced() { var result = "avalue".ReplaceWith("a", "b"); - result.Should().Be("bvblue"); + result.Should() + .Be("bvblue"); } [Fact] @@ -216,13 +237,16 @@ public void WhenToBoolAndEmpty_ThenReturnsFalse() { var result = "".ToBool(); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenToBoolAndNotMatches_ThenThrows() { - "notavalue".Invoking(x => x.ToBool()).Should().Throw(); + "notavalue".Invoking(x => x.ToBool()) + .Should() + .Throw(); } [Fact] @@ -230,7 +254,8 @@ public void WhenToBoolAndMatchesLowercase_ThenReturnsTrue() { var result = "true".ToBool(); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -238,7 +263,8 @@ public void WhenToBoolAndMatchesUppercase_ThenReturnsTrue() { var result = "TRUE".ToBool(); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -246,7 +272,8 @@ public void WhenToBoolAndMatchesMixedcase_ThenReturnsTrue() { var result = "True".ToBool(); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -254,7 +281,8 @@ public void WhenToBoolOrDefaultAndEmpty_ThenReturnsDefault() { var result = "".ToBoolOrDefault(true); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -262,7 +290,8 @@ public void WhenToBoolOrDefaultAndNotMatches_ThenReturnsDefault() { var result = "notavalue".ToBoolOrDefault(true); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -270,7 +299,8 @@ public void WhenToBoolOrDefaultAndMatchesLowercase_ThenReturnsMatched() { var result = "false".ToBoolOrDefault(true); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -278,7 +308,8 @@ public void WhenToBoolOrDefaultAndMatchesUppercase_ThenReturnsMatched() { var result = "FALSE".ToBoolOrDefault(true); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -286,7 +317,8 @@ public void WhenToBoolOrDefaultAndMatchesMixedcase_ThenReturnsMatched() { var result = "False".ToBoolOrDefault(true); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -294,13 +326,16 @@ public void WhenToIntAndEmpty_ThenReturnsMinusOne() { var result = "".ToInt(); - result.Should().Be(-1); + result.Should() + .Be(-1); } [Fact] public void WhenToIntAndNotMatches_ThenThrows() { - "notavalue".Invoking(x => x.ToInt()).Should().Throw(); + "notavalue".Invoking(x => x.ToInt()) + .Should() + .Throw(); } [Fact] @@ -308,7 +343,8 @@ public void WhenToIntAndMatchesLowercase_ThenReturnsTrue() { var result = "9".ToInt(); - result.Should().Be(9); + result.Should() + .Be(9); } [Fact] @@ -316,7 +352,8 @@ public void WhenToIntOrDefaultAndEmpty_ThenReturnsDefault() { var result = "".ToIntOrDefault(9); - result.Should().Be(9); + result.Should() + .Be(9); } [Fact] @@ -324,6 +361,7 @@ public void WhenToIntOrDefaultAndNotMatches_ThenReturnsDefault() { var result = "notavalue".ToIntOrDefault(9); - result.Should().Be(9); + result.Should() + .Be(9); } } \ No newline at end of file diff --git a/src/Common.UnitTests/OptionalSpec.cs b/src/Common.UnitTests/OptionalSpec.cs index 0094cbfa..9498baa2 100644 --- a/src/Common.UnitTests/OptionalSpec.cs +++ b/src/Common.UnitTests/OptionalSpec.cs @@ -11,9 +11,14 @@ public void WhenConstructedWithoutAnyValue_ThenHasNoValue() { var result = new Optional(); - result.HasValue.Should().BeFalse(); - result.TryGet(out _).Should().BeFalse(); - result.ToString().Should().Be(Optional.NoValueStringValue); + result.HasValue.Should() + .BeFalse(); + result.TryGet(out _) + .Should() + .BeFalse(); + result.ToString() + .Should() + .Be(Optional.NoValueStringValue); } [Fact] @@ -21,9 +26,14 @@ public void WhenConstructedWithNullInstance_ThenHasNoValue() { var result = new Optional(null!); - result.HasValue.Should().BeFalse(); - result.TryGet(out _).Should().BeFalse(); - result.ToString().Should().Be(Optional.NoValueStringValue); + result.HasValue.Should() + .BeFalse(); + result.TryGet(out _) + .Should() + .BeFalse(); + result.ToString() + .Should() + .Be(Optional.NoValueStringValue); } [Fact] @@ -32,9 +42,13 @@ public void WhenConstructedWithAnyValue_ThenHasValue() var instance = new TestClass { AProperty = "avalue" }; var result = new Optional(instance); - result.HasValue.Should().BeTrue(); - result.Value.Should().Be(instance); - result.ToString().Should().Be(typeof(TestClass).FullName); + result.HasValue.Should() + .BeTrue(); + result.Value.Should() + .Be(instance); + result.ToString() + .Should() + .Be(typeof(TestClass).FullName); } [Fact] @@ -42,7 +56,9 @@ public void WhenGetValueAndNullInstance_ThenThrows() { var optional = new Optional(null!); - optional.Invoking(x => x.Value).Should().Throw() + optional.Invoking(x => x.Value) + .Should() + .Throw() .WithMessage(Resources.Optional_NullValue); } @@ -54,7 +70,8 @@ public void WhenGetValue_ThenReturnsValue() var result = optional.Value; - result.Should().Be(instance); + result.Should() + .Be(instance); } [Fact] @@ -64,7 +81,8 @@ public void WhenGetValueOrDefaultAndNullInstance_ThenReturnsNull() var result = optional.ValueOrDefault; - result.Should().BeNull(); + result.Should() + .BeNull(); } [Fact] @@ -75,7 +93,8 @@ public void WhenGetValueOrDefault_ThenReturnsValue() var result = optional.ValueOrDefault; - result.Should().Be(instance); + result.Should() + .Be(instance); } [Fact] @@ -84,7 +103,8 @@ public void WhenEqualsOperatorWithEmptyOptionalAndWithNone_ThenReturnsTrue() var optional1 = new Optional(); var optional2 = Optional.None; - (optional1 == optional2).Should().BeTrue(); + (optional1 == optional2).Should() + .BeTrue(); } [Fact] @@ -93,7 +113,8 @@ public void WhenEqualsOperatorWithNoneAndWithNone_ThenReturnsTrue() var optional1 = Optional.None; var optional2 = Optional.None; - (optional1 == optional2).Should().BeTrue(); + (optional1 == optional2).Should() + .BeTrue(); } [Fact] @@ -102,7 +123,8 @@ public void WhenEqualsOperatorWithEmptyOptionals_ThenReturnsTrue() var optional1 = new Optional(); var optional2 = new Optional(); - (optional1 == optional2).Should().BeTrue(); + (optional1 == optional2).Should() + .BeTrue(); } [Fact] @@ -112,7 +134,8 @@ public void WhenEqualsOperatorWithSameOptionals_ThenReturnsTrue() var optional1 = new Optional(instance); var optional2 = new Optional(instance); - (optional1 == optional2).Should().BeTrue(); + (optional1 == optional2).Should() + .BeTrue(); } [Fact] @@ -121,7 +144,8 @@ public void WhenEqualsOperatorWithEmptyOptionalOfSameType_ThenReturnsFalse() var instance = new TestClass { AProperty = "avalue" }; var optional = new Optional(); - (instance == optional).Should().BeFalse(); + (instance == optional).Should() + .BeFalse(); } [Fact] @@ -129,7 +153,8 @@ public void WhenEqualsOperatorWithNull_ThenReturnsFalse() { var instance = new TestClass { AProperty = "avalue" }; - (instance == null!).Should().BeFalse(); + (instance == null!).Should() + .BeFalse(); } [Fact] @@ -138,7 +163,8 @@ public void WhenEqualsOperatorOptionalOfInstance_ThenReturnsTrue() var instance = new TestClass { AProperty = "avalue" }; var optional = new Optional(instance); - (optional == instance).Should().BeTrue(); + (optional == instance).Should() + .BeTrue(); } [Fact] @@ -147,7 +173,8 @@ public void WhenNotEqualsOperatorWithEmptyOptionalOfSameType_ThenReturnsTrue() var instance = new TestClass { AProperty = "avalue" }; var optional = new Optional(); - (instance != optional).Should().BeTrue(); + (instance != optional).Should() + .BeTrue(); } [Fact] @@ -155,7 +182,8 @@ public void WhenNotEqualsOperatorWithNull_ThenReturnsTrue() { var instance = new TestClass { AProperty = "avalue" }; - (instance != null!).Should().BeTrue(); + (instance != null!).Should() + .BeTrue(); } [Fact] @@ -164,7 +192,8 @@ public void WhenNotEqualsOperatorOptionalOfInstance_ThenReturnsFalse() var instance = new TestClass { AProperty = "avalue" }; var optional = new Optional(instance); - (optional != instance).Should().BeFalse(); + (optional != instance).Should() + .BeFalse(); } [Fact] @@ -173,7 +202,9 @@ public void WhenEqualsWithEmptyOptionalOfSameType_ThenReturnsFalse() var instance = new TestClass { AProperty = "avalue" }; var optional = new Optional(); - optional.Equals(instance).Should().BeFalse(); + optional.Equals(instance) + .Should() + .BeFalse(); } [Fact] @@ -181,7 +212,9 @@ public void WhenEqualsWithNull_ThenReturnsFalse() { var instance = new TestClass { AProperty = "avalue" }; - instance.Equals(null!).Should().BeFalse(); + instance.Equals(null!) + .Should() + .BeFalse(); } [Fact] @@ -190,7 +223,9 @@ public void WhenEqualsOptionalOfInstance_ThenReturnsTrue() var instance = new TestClass { AProperty = "avalue" }; var optional = new Optional(instance); - optional.Equals(instance).Should().BeTrue(); + optional.Equals(instance) + .Should() + .BeTrue(); } [Fact] @@ -200,7 +235,9 @@ public void WhenObjectEqualsBetweenNullOptionalAndInstance_ThenReturnsFalse() var optional = new Optional(null!); // ReSharper disable once SuspiciousTypeConversion.Global - optional.Equals((object?)instance).Should().BeFalse(); + optional.Equals((object?)instance) + .Should() + .BeFalse(); } [Fact] @@ -210,7 +247,9 @@ public void WhenObjectEqualsBetweenEmptyOptionalAndInstanceOfSameType_ThenReturn var optional = new Optional(); // ReSharper disable once SuspiciousTypeConversion.Global - optional.Equals((object?)instance).Should().BeFalse(); + optional.Equals((object?)instance) + .Should() + .BeFalse(); } [Fact] @@ -220,7 +259,9 @@ public void WhenObjectEqualsBetweenOptionOfInstanceAndInstance_ThenReturnsTrue() var optional = new Optional(instance); // ReSharper disable once SuspiciousTypeConversion.Global - optional.Equals((object?)instance).Should().BeTrue(); + optional.Equals((object?)instance) + .Should() + .BeTrue(); } [Fact] @@ -229,7 +270,9 @@ public void WhenObjectEqualsBetweenOptionalOfInstanceAndOptionalOfInstance_ThenR var instance = new TestClass { AProperty = "avalue" }; var optional = new Optional(instance); - optional.Equals((object?)optional).Should().BeTrue(); + optional.Equals((object?)optional) + .Should() + .BeTrue(); } } diff --git a/src/Common.UnitTests/ResultSpec.cs b/src/Common.UnitTests/ResultSpec.cs index 3caa0650..89079671 100644 --- a/src/Common.UnitTests/ResultSpec.cs +++ b/src/Common.UnitTests/ResultSpec.cs @@ -16,7 +16,8 @@ public void WhenConstructedWithNullScalarValue_ThenInitialized() { var result = new Result(null!); - result.IsSuccessful.Should().BeTrue(); + result.IsSuccessful.Should() + .BeTrue(); } [Fact] @@ -24,7 +25,8 @@ public void WhenConstructedWithAnyScalarValue_ThenInitialized() { var result = new Result(string.Empty); - result.IsSuccessful.Should().BeTrue(); + result.IsSuccessful.Should() + .BeTrue(); } [Fact] @@ -32,7 +34,8 @@ public void WhenConstructedWithEmptyOptionalValue_ThenInitialized() { var result = new Result(new Optional()); - result.IsSuccessful.Should().BeTrue(); + result.IsSuccessful.Should() + .BeTrue(); } [Fact] @@ -40,7 +43,8 @@ public void WhenConstructedWithAnyOptionalValue_ThenInitialized() { var result = new Result(new Optional(string.Empty)); - result.IsSuccessful.Should().BeTrue(); + result.IsSuccessful.Should() + .BeTrue(); } [Fact] @@ -48,7 +52,8 @@ public void WhenConstructedWithAnyError_ThenInitialized() { var result = new Result(new TestError()); - result.IsSuccessful.Should().BeFalse(); + result.IsSuccessful.Should() + .BeFalse(); } [Fact] @@ -56,7 +61,9 @@ public void WhenGetValueAndFaulted_ThenThrows() { var result = new Result(new TestError()); - result.Invoking(x => x.Value).Should().Throw() + result.Invoking(x => x.Value) + .Should() + .Throw() .WithMessage(Resources.Result_FetchValueWhenFaulted.Format("atesterror")); } @@ -67,7 +74,8 @@ public void WhenGetValue_ThenReturnsValue() var actual = result.Value; - actual.Should().Be("avalue"); + actual.Should() + .Be("avalue"); } [Fact] @@ -75,7 +83,9 @@ public void WhenGetErrorAndNotFaulted_ThenThrows() { var result = new Result("avalue"); - result.Invoking(x => x.Error).Should().Throw() + result.Invoking(x => x.Error) + .Should() + .Throw() .WithMessage(Resources.Result_FetchErrorWhenNotFaulted); } @@ -87,7 +97,8 @@ public void WhenGetError_ThenReturnsValue() var actual = result.Error; - actual.Should().Be(error); + actual.Should() + .Be(error); } [Fact] @@ -97,7 +108,8 @@ public void WhenHasValueAndFaulted_ThenReturnsFalse() var actual = result.HasValue; - actual.Should().BeFalse(); + actual.Should() + .BeFalse(); } [Fact] @@ -107,7 +119,8 @@ public void WhenHasValueAndNotFaultedWithNull_ThenReturnsFalse() var actual = result.HasValue; - actual.Should().BeFalse(); + actual.Should() + .BeFalse(); } [Fact] @@ -117,7 +130,8 @@ public void WhenHasValueAndNotFaultedWithValue_ThenReturnsTrue() var actual = result.HasValue; - actual.Should().BeTrue(); + actual.Should() + .BeTrue(); } [Fact] @@ -127,7 +141,8 @@ public void WhenExistsAndFaulted_ThenReturnsFalse() var actual = result.Exists; - actual.Should().BeFalse(); + actual.Should() + .BeFalse(); } [Fact] @@ -137,7 +152,8 @@ public void WhenExistsAndNotFaultedWithNull_ThenReturnsFalse() var actual = result.Exists; - actual.Should().BeFalse(); + actual.Should() + .BeFalse(); } [Fact] @@ -147,7 +163,8 @@ public void WhenExistsAndNotFaultedWithValue_ThenReturnsTrue() var actual = result.Exists; - actual.Should().BeTrue(); + actual.Should() + .BeTrue(); } [Fact] @@ -157,7 +174,8 @@ public void WhenFromErrorWithError_ThenReturnsResultOfError() var result = Result.FromError(error); - result.Error.Should().Be(error); + result.Error.Should() + .Be(error); } [Fact] @@ -165,7 +183,8 @@ public void WhenFromValueWithValue_ThenReturnsResultOfValue() { var result = Result.FromResult("avalue"); - result.Value.Should().Be("avalue"); + result.Value.Should() + .Be("avalue"); } [Fact] @@ -176,8 +195,10 @@ public void WhenTryGetOutAndIsFaulted_ThenReturnsFalse() var actual = result.TryGet(out var assigned); - actual.Should().BeFalse(); - assigned.Should().Be(null); + actual.Should() + .BeFalse(); + assigned.Should() + .Be(null); } [Fact] @@ -187,8 +208,10 @@ public void WhenTryGetOutAndIsNotFaulted_ThenReturnsTrue() var actual = result.TryGet(out var assigned); - actual.Should().BeTrue(); - assigned.Should().Be("avalue"); + actual.Should() + .BeTrue(); + assigned.Should() + .Be("avalue"); } [Fact] @@ -198,8 +221,10 @@ public void WhenTryGetErrorAndIsNotFaulted_ThenReturnsFalse() var actual = result.TryGetError(out var assigned); - actual.Should().BeFalse(); - assigned.Should().Be(null); + actual.Should() + .BeFalse(); + assigned.Should() + .Be(null); } [Fact] @@ -210,8 +235,10 @@ public void WhenTryGetErrorAndIsFaulted_ThenReturnsTrue() var actual = result.TryGetError(out var assigned); - actual.Should().BeTrue(); - assigned.Should().Be(error); + actual.Should() + .BeTrue(); + assigned.Should() + .Be(error); } [Fact] @@ -222,7 +249,8 @@ public void WhenToStringAndFaulted_ThenReturnsErrorRepresentation() var actual = result.ToString(); - actual.Should().Be("atesterror"); + actual.Should() + .Be("atesterror"); } [Fact] @@ -232,7 +260,8 @@ public void WhenToStringAndNotFaulted_ThenReturnsValueRepresentation() var actual = result.ToString(); - actual.Should().Be("avalue"); + actual.Should() + .Be("avalue"); } [Fact] @@ -240,8 +269,10 @@ public void WhenCastAnyValueToResultOfThatValue_ThenReturnsResultOfThatValue() { var result = (Result)"avalue"; - result.IsSuccessful.Should().BeTrue(); - result.Value.Should().Be("avalue"); + result.IsSuccessful.Should() + .BeTrue(); + result.Value.Should() + .Be("avalue"); } [Fact] @@ -251,8 +282,10 @@ public void WhenCastAnyErrorToResultOfThatError_ThenReturnsResultOfThatError() var result = (Result)error; - result.IsSuccessful.Should().BeFalse(); - result.Error.Should().Be(error); + result.IsSuccessful.Should() + .BeFalse(); + result.Error.Should() + .Be(error); } [Fact] @@ -262,7 +295,8 @@ public void WhenCastAnyResultOfValueToTypeOfValue_ThenReturnsValue() var actual = (string)result; - actual.Should().Be("avalue"); + actual.Should() + .Be("avalue"); } [Fact] @@ -273,7 +307,8 @@ public void WhenBitwiseAndResultsThatAreNotBothSuccessful_ThenReturnsFalse() var actual = result1 & result2; - actual.Should().BeFalse(); + actual.Should() + .BeFalse(); } [Fact] @@ -284,7 +319,8 @@ public void WhenBitwiseAndingResultsThatAreBothSuccessful_ThenReturnsTrue() var actual = result1 & result2; - actual.Should().BeTrue(); + actual.Should() + .BeTrue(); } [Fact] @@ -307,10 +343,14 @@ public void WhenMatchAndSuccessfulContainingNullValue_ThenReturnsOptionalNone() return false; }); - match.Should().BeTrue(); - successWasCalled.Should().BeTrue(); - errorWasCalled.Should().BeFalse(); - passedValue.Should().Be(Optional.None); + match.Should() + .BeTrue(); + successWasCalled.Should() + .BeTrue(); + errorWasCalled.Should() + .BeFalse(); + passedValue.Should() + .Be(Optional.None); } [Fact] @@ -333,10 +373,14 @@ public void WhenMatchAndSuccessfulContainingNonNullValue_ThenReturnsTheOptionalV return false; }); - match.Should().BeTrue(); - successWasCalled.Should().BeTrue(); - errorWasCalled.Should().BeFalse(); - passedValue.Should().Be("avalue"); + match.Should() + .BeTrue(); + successWasCalled.Should() + .BeTrue(); + errorWasCalled.Should() + .BeFalse(); + passedValue.Should() + .Be("avalue"); } [Fact] @@ -360,10 +404,14 @@ public void WhenMatchAndNotSuccessful_ThenReturnsTheError() return true; }); - match.Should().BeTrue(); - successWasCalled.Should().BeFalse(); - errorWasCalled.Should().BeTrue(); - passedValue.Should().Be(error); + match.Should() + .BeTrue(); + successWasCalled.Should() + .BeFalse(); + errorWasCalled.Should() + .BeTrue(); + passedValue.Should() + .Be(error); } } @@ -375,7 +423,8 @@ public void WhenConstructedWithNoValue_ThenInitialized() { var result = new Result(); - result.IsSuccessful.Should().BeTrue(); + result.IsSuccessful.Should() + .BeTrue(); } [Fact] @@ -383,7 +432,8 @@ public void WhenConstructedWithAnyError_ThenInitialized() { var result = new Result(new TestError()); - result.IsSuccessful.Should().BeFalse(); + result.IsSuccessful.Should() + .BeFalse(); } [Fact] @@ -391,7 +441,9 @@ public void WhenGetErrorAndNotFaulted_ThenThrows() { var result = new Result(); - result.Invoking(x => x.Error).Should().Throw() + result.Invoking(x => x.Error) + .Should() + .Throw() .WithMessage(Resources.Result_FetchErrorWhenNotFaulted); } @@ -403,7 +455,8 @@ public void WhenGetError_ThenReturnsValue() var actual = result.Error; - actual.Should().Be(error); + actual.Should() + .Be(error); } [Fact] @@ -413,7 +466,8 @@ public void WhenFromErrorWithError_ThenReturnsResultOfError() var result = Result.FromError(error); - result.Error.Should().Be(error); + result.Error.Should() + .Be(error); } [Fact] @@ -423,8 +477,10 @@ public void WhenTryGetErrorAndIsNotFaulted_ThenReturnsFalse() var actual = result.TryGetError(out var assigned); - actual.Should().BeFalse(); - assigned.Should().Be(null); + actual.Should() + .BeFalse(); + assigned.Should() + .Be(null); } [Fact] @@ -435,8 +491,10 @@ public void WhenTryGetErrorAndIsFaulted_ThenReturnsTrue() var actual = result.TryGetError(out var assigned); - actual.Should().BeTrue(); - assigned.Should().Be(error); + actual.Should() + .BeTrue(); + assigned.Should() + .Be(error); } [Fact] @@ -447,7 +505,8 @@ public void WhenToStringAndFaulted_ThenReturnsErrorRepresentation() var actual = result.ToString(); - actual.Should().Be("atesterror"); + actual.Should() + .Be("atesterror"); } [Fact] @@ -457,7 +516,8 @@ public void WhenToStringAndNotFaulted_ThenReturnsValueRepresentation() var actual = result.ToString(); - actual.Should().Be("OK"); + actual.Should() + .Be("OK"); } [Fact] @@ -467,8 +527,10 @@ public void WhenCastAnyErrorToResultOfThatError_ThenReturnsResultOfThatError() var result = (Result)error; - result.IsSuccessful.Should().BeFalse(); - result.Error.Should().Be(error); + result.IsSuccessful.Should() + .BeFalse(); + result.Error.Should() + .Be(error); } [Fact] @@ -479,7 +541,8 @@ public void WhenBitwiseAndResultsThatAreNotBothSuccessful_ThenReturnsFalse() var actual = result1 & result2; - actual.Should().BeFalse(); + actual.Should() + .BeFalse(); } [Fact] @@ -490,7 +553,8 @@ public void WhenBitwiseAndingResultsThatAreBothSuccessful_ThenReturnsTrue() var actual = result1 & result2; - actual.Should().BeTrue(); + actual.Should() + .BeTrue(); } [Fact] @@ -513,10 +577,14 @@ public void WhenMatchAndSuccessful_ThenReturnsTrue() return false; }); - match.Should().BeTrue(); - successWasCalled.Should().BeTrue(); - errorWasCalled.Should().BeFalse(); - passedValue.Should().BeNull(); + match.Should() + .BeTrue(); + successWasCalled.Should() + .BeTrue(); + errorWasCalled.Should() + .BeFalse(); + passedValue.Should() + .BeNull(); } [Fact] @@ -540,10 +608,14 @@ public void WhenMatchAndNotSuccessful_ThenReturnsTheError() return true; }); - match.Should().BeTrue(); - successWasCalled.Should().BeFalse(); - errorWasCalled.Should().BeTrue(); - passedValue.Should().Be(error); + match.Should() + .BeTrue(); + successWasCalled.Should() + .BeFalse(); + errorWasCalled.Should() + .BeTrue(); + passedValue.Should() + .Be(error); } } } diff --git a/src/Common/Annotations.cs b/src/Common/Annotations.cs index 3af1658c..08995e25 100644 --- a/src/Common/Annotations.cs +++ b/src/Common/Annotations.cs @@ -51,10 +51,9 @@ namespace JetBrains.Annotations; /// } /// /// -[AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | - AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | - AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property + | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class + | AttributeTargets.Interface | AttributeTargets.GenericParameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class CanBeNullAttribute : Attribute { @@ -70,10 +69,9 @@ public sealed class CanBeNullAttribute : Attribute /// } /// /// -[AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | - AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | - AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.GenericParameter)] +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property + | AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Class + | AttributeTargets.Interface | AttributeTargets.GenericParameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class NotNullAttribute : Attribute { @@ -95,9 +93,8 @@ public sealed class NotNullAttribute : Attribute /// } /// /// -[AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | - AttributeTargets.Delegate | AttributeTargets.Field)] +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property + | AttributeTargets.Delegate | AttributeTargets.Field)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class ItemNotNullAttribute : Attribute { @@ -120,9 +117,8 @@ public sealed class ItemNotNullAttribute : Attribute /// } /// /// -[AttributeUsage( - AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property | - AttributeTargets.Delegate | AttributeTargets.Field)] +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property + | AttributeTargets.Delegate | AttributeTargets.Field)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class ItemCanBeNullAttribute : Attribute { @@ -143,9 +139,8 @@ public sealed class ItemCanBeNullAttribute : Attribute /// } /// /// -[AttributeUsage( - AttributeTargets.Constructor | AttributeTargets.Method | - AttributeTargets.Property | AttributeTargets.Delegate)] +[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property + | AttributeTargets.Delegate)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class StringFormatMethodAttribute : Attribute { @@ -209,9 +204,7 @@ public sealed class StructuredMessageTemplateAttribute : Attribute /// } /// /// -[AttributeUsage( - AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field, - AllowMultiple = true)] +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class ValueProviderAttribute : Attribute { @@ -238,9 +231,8 @@ public ValueProviderAttribute([NotNull] string name) /// /// [AttributeUsage( - AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property | - AttributeTargets.Method | AttributeTargets.Delegate, - AllowMultiple = true)] + AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method + | AttributeTargets.Delegate, AllowMultiple = true)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class ValueRangeAttribute : Attribute { @@ -283,9 +275,8 @@ public ValueRangeAttribute(ulong value) /// } /// /// -[AttributeUsage( - AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property | - AttributeTargets.Method | AttributeTargets.Delegate)] +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property + | AttributeTargets.Method | AttributeTargets.Delegate)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class NonNegativeValueAttribute : Attribute { @@ -443,8 +434,7 @@ public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class ContractAnnotationAttribute : Attribute { - public ContractAnnotationAttribute([NotNull] string contract) - : this(contract, false) + public ContractAnnotationAttribute([NotNull] string contract) : this(contract, false) { } @@ -565,18 +555,16 @@ public BaseTypeRequiredAttribute([NotNull] Type baseType) [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class UsedImplicitlyAttribute : Attribute { - public UsedImplicitlyAttribute() - : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) + public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } - public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) - : this(useKindFlags, ImplicitUseTargetFlags.Default) + public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, + ImplicitUseTargetFlags.Default) { } - public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) - : this(ImplicitUseKindFlags.Default, targetFlags) + public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } @@ -602,18 +590,17 @@ public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTar [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class MeansImplicitUseAttribute : Attribute { - public MeansImplicitUseAttribute() - : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) + public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } - public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) - : this(useKindFlags, ImplicitUseTargetFlags.Default) + public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, + ImplicitUseTargetFlags.Default) { } - public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) - : this(ImplicitUseKindFlags.Default, targetFlags) + public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, + targetFlags) { } @@ -799,9 +786,9 @@ public sealed class RequireStaticDelegateAttribute : Attribute /// } /// /// -[AttributeUsage( - AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.Method | - AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.GenericParameter)] +[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter + | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface + | AttributeTargets.Struct | AttributeTargets.GenericParameter)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class ProvidesContextAttribute : Attribute { @@ -945,8 +932,8 @@ public sealed class MacroAttribute : Attribute /// } /// /// -[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property | - AttributeTargets.ReturnValue)] +[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property + | AttributeTargets.ReturnValue)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class CollectionAccessAttribute : Attribute { @@ -1147,8 +1134,7 @@ public LanguageInjectionAttribute([NotNull] string injectedLanguage) /// /// The attribute must be mentioned in your member reordering patterns. /// -[AttributeUsage( - AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)] +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct | AttributeTargets.Enum)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class NoReorderAttribute : Attribute { @@ -1344,17 +1330,9 @@ public sealed class NoReorderAttribute : Attribute /// /// [AttributeUsage( - AttributeTargets.Method - | AttributeTargets.Constructor - | AttributeTargets.Property - | AttributeTargets.Field - | AttributeTargets.Event - | AttributeTargets.Interface - | AttributeTargets.Class - | AttributeTargets.Struct - | AttributeTargets.Enum, - AllowMultiple = true, - Inherited = false)] + AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property | AttributeTargets.Field + | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct + | AttributeTargets.Enum, AllowMultiple = true, Inherited = false)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class CodeTemplateAttribute : Attribute { @@ -1579,8 +1557,8 @@ public AspMvcViewLocationFormatAttribute([NotNull] string format) /// implicitly from the context. Use this attribute for custom wrappers similar to /// System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String). /// -[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | - AttributeTargets.Property)] +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field + | AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcActionAttribute : Attribute { @@ -1623,8 +1601,8 @@ public AspMvcAreaAttribute([NotNull] string anonymousProperty) /// implicitly from the context. Use this attribute for custom wrappers similar to /// System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String). /// -[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | - AttributeTargets.Property)] +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field + | AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcControllerAttribute : Attribute { @@ -1666,8 +1644,8 @@ public sealed class AspMvcModelTypeAttribute : Attribute /// from the context. Use this attribute for custom wrappers similar to /// System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String). /// -[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | - AttributeTargets.Property)] +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field + | AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcPartialViewAttribute : Attribute { @@ -1721,8 +1699,8 @@ public sealed class AspMvcTemplateAttribute : Attribute /// from the context. Use this attribute for custom wrappers similar to /// System.Web.Mvc.Controller.View(Object). /// -[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | - AttributeTargets.Property)] +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field + | AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcViewAttribute : Attribute { @@ -1742,8 +1720,8 @@ public sealed class AspMvcViewComponentAttribute : Attribute /// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter /// is an MVC view component view. If applied to a method, the MVC view component view name is default. /// -[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field | - AttributeTargets.Property)] +[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Field + | AttributeTargets.Property)] [Conditional("JETBRAINS_ANNOTATIONS")] public sealed class AspMvcViewComponentViewAttribute : Attribute { diff --git a/src/Common/Common.csproj b/src/Common/Common.csproj index c6e0bd51..65c71b6b 100644 --- a/src/Common/Common.csproj +++ b/src/Common/Common.csproj @@ -26,4 +26,11 @@ <_Parameter1>$(AssemblyName).UnitTests + + + + + diff --git a/src/Common/Extensions/DateTimeExtensions.cs b/src/Common/Extensions/DateTimeExtensions.cs index b4965803..b7f0dd99 100644 --- a/src/Common/Extensions/DateTimeExtensions.cs +++ b/src/Common/Extensions/DateTimeExtensions.cs @@ -27,7 +27,9 @@ public static DateTime FromIso8601(this string? value) if (DateTime.TryParseExact(value!, supportedIsoFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out var date)) { - return date.Kind == DateTimeKind.Utc ? date : date.ToUniversalTime(); + return date.Kind == DateTimeKind.Utc + ? date + : date.ToUniversalTime(); } return default; @@ -100,7 +102,8 @@ public static long ToUnixMilliSeconds(this DateTime value) ? value : value.ToUniversalTime(); - return (long)utcDateTime.Subtract(DateTime.UnixEpoch).TotalMilliseconds; + return (long)utcDateTime.Subtract(DateTime.UnixEpoch) + .TotalMilliseconds; } /// @@ -125,7 +128,8 @@ public static long ToUnixSeconds(this DateTime value) ? value : value.ToUniversalTime(); - return utcDateTime.Subtract(DateTime.UnixEpoch).Ticks / TimeSpan.TicksPerSecond; + return utcDateTime.Subtract(DateTime.UnixEpoch) + .Ticks / TimeSpan.TicksPerSecond; } /// diff --git a/src/Common/Extensions/DictionaryExtensions.cs b/src/Common/Extensions/DictionaryExtensions.cs index 4a580134..27aaca67 100644 --- a/src/Common/Extensions/DictionaryExtensions.cs +++ b/src/Common/Extensions/DictionaryExtensions.cs @@ -9,6 +9,7 @@ public static class DictionaryExtensions public static void Merge(this IDictionary source, IDictionary other) where TKey : notnull { - other.ToList().ForEach(entry => { source.TryAdd(entry.Key, entry.Value); }); + other.ToList() + .ForEach(entry => { source.TryAdd(entry.Key, entry.Value); }); } } \ No newline at end of file diff --git a/src/Common/Extensions/EnumExtensions.cs b/src/Common/Extensions/EnumExtensions.cs index 916a98dc..f0cb892c 100644 --- a/src/Common/Extensions/EnumExtensions.cs +++ b/src/Common/Extensions/EnumExtensions.cs @@ -14,10 +14,10 @@ public static TTargetEnum ToEnum(this string value) /// Converts the value of the to a value in the /// public static TTargetEnum ToEnum(this TSourceEnum source) - where TSourceEnum : Enum - where TTargetEnum : Enum + where TSourceEnum : Enum where TTargetEnum : Enum { - return source.ToString().ToEnum(); + return source.ToString() + .ToEnum(); } /// @@ -45,8 +45,7 @@ public static TTargetEnum ToEnumOrDefault(this string value, TTarge /// public static TTargetEnum ToEnumOrDefault(this TSourceEnum source, TTargetEnum defaultValue) - where TSourceEnum : Enum - where TTargetEnum : Enum + where TSourceEnum : Enum where TTargetEnum : Enum { var sourceValue = source.ToString(); if (Enum.TryParse(typeof(TTargetEnum), sourceValue, true, out var converted)) diff --git a/src/Common/IRecorder.cs b/src/Common/IRecorder.cs index e9f34a61..2a12a1a6 100644 --- a/src/Common/IRecorder.cs +++ b/src/Common/IRecorder.cs @@ -17,7 +17,7 @@ void AuditAgainst(ICallContext? context, string againstId, string auditCode, str void Crash(ICallContext? context, CrashLevel level, Exception exception, string messageTemplate, params object[] templateArgs); - void Measure(string eventName, Dictionary? context = null); + void Measure(string eventName, Dictionary? additional = null); void TraceDebug(ICallContext? context, string messageTemplate, params object[] templateArgs); @@ -30,8 +30,7 @@ void TraceInformation(ICallContext? context, Exception exception, string message void TraceInformation(ICallContext? context, string messageTemplate, params object[] templateArgs); - void TraceWarning(ICallContext? context, Exception exception, string messageTemplate, - params object[] templateArgs); + void TraceWarning(ICallContext? context, Exception exception, string messageTemplate, params object[] templateArgs); void TraceWarning(ICallContext? context, string messageTemplate, params object[] templateArgs); diff --git a/src/Common/Reflector.cs b/src/Common/Reflector.cs index 1db18de8..58958233 100644 --- a/src/Common/Reflector.cs +++ b/src/Common/Reflector.cs @@ -14,7 +14,8 @@ public static class Reflector /// public static string GetPropertyName(Expression> property) { - return GetProperty(property).Name; + return GetProperty(property) + .Name; } private static PropertyInfo GetProperty(Expression> property) diff --git a/src/Domain.Common.UnitTests/NamePrefixedIdentifierFactorySpec.cs b/src/Domain.Common.UnitTests/NamePrefixedIdentifierFactorySpec.cs index b37b58fb..c4f11de2 100644 --- a/src/Domain.Common.UnitTests/NamePrefixedIdentifierFactorySpec.cs +++ b/src/Domain.Common.UnitTests/NamePrefixedIdentifierFactorySpec.cs @@ -18,7 +18,9 @@ public void WhenCreateWithUnknownEntityType_ThenReturnsGuid() { var result = _factory.Create(new UnknownEntity()); - result.ToString().Should().MatchRegex(@"xxx_[\d\w]{10,22}"); + result.ToString() + .Should() + .MatchRegex(@"xxx_[\d\w]{10,22}"); } [Fact] @@ -26,7 +28,9 @@ public void WhenCreateWithKnownEntity_ThenReturnsId() { var result = _factory.Create(new KnownEntity()); - result.ToString().Should().MatchRegex(@"kno_[\d\w]{10,22}"); + result.ToString() + .Should() + .MatchRegex(@"kno_[\d\w]{10,22}"); } [Fact] @@ -34,7 +38,8 @@ public void WhenIsValidWithTooShortId_ThenReturnsFalse() { var result = _factory.IsValid(Identifier.Create("tooshort")); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -42,7 +47,8 @@ public void WhenIsValidWithInvalidPrefix_ThenReturnsFalse() { var result = _factory.IsValid(Identifier.Create("999_123456789012")); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -50,7 +56,8 @@ public void WhenIsValidWithTooShortRandomPart_ThenReturnsFalse() { var result = _factory.IsValid(Identifier.Create("xxx_123456789")); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -58,7 +65,8 @@ public void WhenIsValidWithTooLongRandomPart_ThenReturnsFalse() { var result = _factory.IsValid(Identifier.Create("xxx_12345678901234567890123")); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -66,7 +74,8 @@ public void WhenIsValidWithUnknownPrefix_ThenReturnsTrue() { var result = _factory.IsValid(Identifier.Create("xxx_123456789012")); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -74,7 +83,8 @@ public void WhenIsValidWithKnownPrefix_ThenReturnsTrue() { var result = _factory.IsValid(Identifier.Create("kno_123456789012")); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -82,7 +92,8 @@ public void WhenIsValidWithAnonymousUserId_ThenReturnsTrue() { var result = _factory.IsValid(CallerConstants.AnonymousUserId.ToIdentifier()); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -92,16 +103,17 @@ public void WhenIsValidWithKnownSupportedPrefix_ThenReturnsTrue() var result = _factory.IsValid(Identifier.Create("another_123456789012")); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenConvertGuidWithKnownGuid_ThenReturnsConverted() { - var id = NamePrefixedIdentifierFactory.ConvertGuid(new Guid("65dd0b02-170b-4ea1-a5a5-00d2808b9aee"), - "known"); + var id = NamePrefixedIdentifierFactory.ConvertGuid(new Guid("65dd0b02-170b-4ea1-a5a5-00d2808b9aee"), "known"); - id.Should().Be("known_AgvdZQsXoU6lpQDSgIua7g"); + id.Should() + .Be("known_AgvdZQsXoU6lpQDSgIua7g"); } } diff --git a/src/Domain.Common/Entities/NamePrefixedIdentifierFactory.cs b/src/Domain.Common/Entities/NamePrefixedIdentifierFactory.cs index 0f1e8308..066b7303 100644 --- a/src/Domain.Common/Entities/NamePrefixedIdentifierFactory.cs +++ b/src/Domain.Common/Entities/NamePrefixedIdentifierFactory.cs @@ -51,8 +51,7 @@ public bool IsValid(Identifier value) } var prefix = id.Substring(0, delimiterIndex); - if (!IsKnownPrefix(prefix) - && prefix != UnknownEntityPrefix) + if (!IsKnownPrefix(prefix) && prefix != UnknownEntityPrefix) { return false; } @@ -90,8 +89,7 @@ internal static string ConvertGuid(Guid guid, string prefix) private bool IsKnownPrefix(string prefix) { - var allPossiblePrefixes = _prefixes - .Select(pre => pre.Value) + var allPossiblePrefixes = _prefixes.Select(pre => pre.Value) .Concat(SupportedPrefixes) .Distinct(); diff --git a/src/Domain.Interfaces.UnitTests/Validations/ValidationsSpec.cs b/src/Domain.Interfaces.UnitTests/Validations/ValidationsSpec.cs index 9964d537..3e54bf81 100644 --- a/src/Domain.Interfaces.UnitTests/Validations/ValidationsSpec.cs +++ b/src/Domain.Interfaces.UnitTests/Validations/ValidationsSpec.cs @@ -10,96 +10,120 @@ public class ValidationsSpec [Fact] public void WhenAnythingWithLeastChars_ThenReturnsTrue() { - var result = CommonValidations.Anything(6, 10).Matches("avalue"); + var result = CommonValidations.Anything(6, 10) + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenAnythingWithMaxChars_ThenReturnsTrue() { - var result = CommonValidations.Anything(2, 6).Matches("avalue"); + var result = CommonValidations.Anything(2, 6) + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenAnythingWithSpecialCharacters_ThenReturnsTrue() { - var result = CommonValidations.Anything().Matches("atext^是⎈𐂯؄💩⚡"); + var result = CommonValidations.Anything() + .Matches("atext^是⎈𐂯؄💩⚡"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenAnythingWithTooLong_ThenReturnsFalse() { - var result = CommonValidations.Anything(2, 10).Matches("atoolongstring"); + var result = CommonValidations.Anything(2, 10) + .Matches("atoolongstring"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenAnythingWithTooShort_ThenReturnsFalse() { - var result = CommonValidations.Anything(2, 10).Matches("a"); - result.Should().BeFalse(); + var result = CommonValidations.Anything(2, 10) + .Matches("a"); + result.Should() + .BeFalse(); } [Fact] public void WhenDescriptiveNameIsEmpty_ThenReturnsFalse() { - var result = CommonValidations.DescriptiveName().Matches(""); + var result = CommonValidations.DescriptiveName() + .Matches(""); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenDescriptiveNameWithInvalidPrintableChar_ThenReturnsFalse() { - var result = CommonValidations.DescriptiveName(2, 10).Matches("^aninvalidstring"); + var result = CommonValidations.DescriptiveName(2, 10) + .Matches("^aninvalidstring"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenDescriptiveNameWithLeastChars_ThenReturnsTrue() { - var result = CommonValidations.DescriptiveName(6, 10).Matches("avalue"); + var result = CommonValidations.DescriptiveName(6, 10) + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenDescriptiveNameWithMaxChars_ThenReturnsTrue() { - var result = CommonValidations.DescriptiveName(2, 6).Matches("avalue"); + var result = CommonValidations.DescriptiveName(2, 6) + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenDescriptiveNameWithTooLong_ThenReturnsFalse() { - var result = CommonValidations.DescriptiveName(2, 10).Matches("atoolongstring"); + var result = CommonValidations.DescriptiveName(2, 10) + .Matches("atoolongstring"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenDescriptiveNameWithTooShort_ThenReturnsFalse() { - var result = CommonValidations.DescriptiveName(2, 10).Matches("a"); + var result = CommonValidations.DescriptiveName(2, 10) + .Matches("a"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenDescriptiveNameWithValidChars_ThenReturnsTrue() { - var result = CommonValidations.DescriptiveName().Matches("avalue"); + var result = CommonValidations.DescriptiveName() + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -107,7 +131,8 @@ public void WhenEmailWithCommonFormat_ThenReturnsTrue() { var result = CommonValidations.EmailAddress.Matches("aname@acompany.com"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -115,7 +140,8 @@ public void WhenEmailWithMultiLevelDomainFormat_ThenReturnsTrue() { var result = CommonValidations.EmailAddress.Matches("aname@anaustraliancompany.com.au"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -123,7 +149,8 @@ public void WhenEmailWithNoName_ThenReturnsFalse() { var result = CommonValidations.EmailAddress.Matches("@company.com"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -131,159 +158,198 @@ public void WhenEmailWithWhitespaceName_ThenReturnsFalse() { var result = CommonValidations.EmailAddress.Matches(" @company.com"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenFreeFormTextWithInvalidPrintableChar_ThenReturnsFalse() { - var result = CommonValidations.FreeformText(2, 10).Matches("^aninvalidstring"); + var result = CommonValidations.FreeformText(2, 10) + .Matches("^aninvalidstring"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenFreeFormTextWithLeastChars_ThenReturnsTrue() { - var result = CommonValidations.FreeformText(6, 10).Matches("avalue"); + var result = CommonValidations.FreeformText(6, 10) + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenFreeFormTextWithMaxChars_ThenReturnsTrue() { - var result = CommonValidations.FreeformText(2, 6).Matches("avalue"); + var result = CommonValidations.FreeformText(2, 6) + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenFreeFormTextWithMultiLineInUnix_ThenReturnsTrue() { - var result = CommonValidations.FreeformText().Matches("\raline1\raline2\r"); + var result = CommonValidations.FreeformText() + .Matches("\raline1\raline2\r"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenFreeFormTextWithMultiLineInWindows_ThenReturnsTrue() { - var result = CommonValidations.FreeformText().Matches("\r\naline1\r\naline2\r\n"); + var result = CommonValidations.FreeformText() + .Matches("\r\naline1\r\naline2\r\n"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenFreeFormTextWithTooLong_ThenReturnsFalse() { - var result = CommonValidations.FreeformText(2, 10).Matches("atoolongstring"); + var result = CommonValidations.FreeformText(2, 10) + .Matches("atoolongstring"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenFreeFormTextWithTooShort_ThenReturnsFalse() { - var result = CommonValidations.FreeformText(2, 10).Matches("a"); + var result = CommonValidations.FreeformText(2, 10) + .Matches("a"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenFreeFormTextWithValidChars_ThenReturnsTrue() { - var result = CommonValidations.FreeformText().Matches("avalue"); + var result = CommonValidations.FreeformText() + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenFreeFormTextWithZeroMinAndEmpty_ThenReturnsTrue() { - var result = CommonValidations.FreeformText(0, 10).Matches(""); + var result = CommonValidations.FreeformText(0, 10) + .Matches(""); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenMarkdownTextWithInvalidPrintableChar_ThenReturnsFalse() { - var result = CommonValidations.Markdown(2, 10).Matches("^aninvalidstring"); + var result = CommonValidations.Markdown(2, 10) + .Matches("^aninvalidstring"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenMarkdownTextWithLeastChars_ThenReturnsTrue() { - var result = CommonValidations.Markdown(6, 10).Matches("avalue"); + var result = CommonValidations.Markdown(6, 10) + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenMarkdownTextWithMaxChars_ThenReturnsTrue() { - var result = CommonValidations.Markdown(2, 6).Matches("avalue"); + var result = CommonValidations.Markdown(2, 6) + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenMarkdownTextWithMultiLineInUnix_ThenReturnsTrue() { - var result = CommonValidations.Markdown().Matches("\raline1\raline2\r"); + var result = CommonValidations.Markdown() + .Matches("\raline1\raline2\r"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenMarkdownTextWithMultiLineInWindows_ThenReturnsTrue() { - var result = CommonValidations.Markdown().Matches("\r\naline1\r\naline2\r\n"); + var result = CommonValidations.Markdown() + .Matches("\r\naline1\r\naline2\r\n"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenMarkdownTextWithTooLong_ThenReturnsFalse() { - var result = CommonValidations.Markdown(2, 10).Matches("atoolongstring"); + var result = CommonValidations.Markdown(2, 10) + .Matches("atoolongstring"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenMarkdownTextWithTooShort_ThenReturnsFalse() { - var result = CommonValidations.Markdown(2, 10).Matches("a"); + var result = CommonValidations.Markdown(2, 10) + .Matches("a"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] public void WhenMarkdownTextWithValidChars_ThenReturnsTrue() { - var result = CommonValidations.Markdown().Matches("avalue"); + var result = CommonValidations.Markdown() + .Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenMarkdownTextWithZeroMinAndEmpty_ThenReturnsTrue() { - var result = CommonValidations.Markdown(0, 10).Matches(""); + var result = CommonValidations.Markdown(0, 10) + .Matches(""); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] public void WhenMarkdownWithValidChars_ThenReturnsTrue() { - var result = CommonValidations.Markdown().Matches("avalue😛"); + var result = CommonValidations.Markdown() + .Matches("avalue😛"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -293,7 +359,8 @@ public void WhenMatchesHasExpression_ThenReturnsTrue() var result = validationFormat.Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -303,7 +370,8 @@ public void WhenMatchesHasExpressionAndIsNotTooLong_ThenReturnsTrue() var result = validationFormat.Matches("aaaaaaa"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } [Fact] @@ -313,7 +381,8 @@ public void WhenMatchesHasExpressionAndIsTooLong_ThenReturnsFalse() var result = validationFormat.Matches("aaaaaaa"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -323,7 +392,8 @@ public void WhenMatchesHasFunction_ThenReturnsFalse() var result = validationFormat.Matches("avalue"); - result.Should().BeFalse(); + result.Should() + .BeFalse(); } [Fact] @@ -333,6 +403,7 @@ public void WhenMatchesHasFunction_ThenReturnsTrue() var result = validationFormat.Matches("avalue"); - result.Should().BeTrue(); + result.Should() + .BeTrue(); } } \ No newline at end of file diff --git a/src/Domain.Interfaces/CallerConstants.cs b/src/Domain.Interfaces/CallerConstants.cs index f5d4855f..c36ff4a2 100644 --- a/src/Domain.Interfaces/CallerConstants.cs +++ b/src/Domain.Interfaces/CallerConstants.cs @@ -5,17 +5,20 @@ namespace Domain.Interfaces; /// public static class CallerConstants { - public const string AnonymousUserId = - "xxx_anonymous0000000000000"; // An account used by anonymous (unauthenticated) users + public const string + AnonymousUserId = "xxx_anonymous0000000000000"; // An account used by anonymous (unauthenticated) users - public const string ExternalWebhookAccountUserId = - "xxx_externalwebhook0000001"; // An account we use to represent inbound webhook calls from 3rd party integrations + public const string + ExternalWebhookAccountUserId = + "xxx_externalwebhook0000001"; // An account we use to represent inbound webhook calls from 3rd party integrations - public const string MaintenanceAccountUserId = - "xxx_maintenance00000000001"; // A service account we use to represent internal calls between distributed services and domain notifications + public const string + MaintenanceAccountUserId = + "xxx_maintenance00000000001"; // A service account we use to represent internal calls between distributed services and domain notifications - public const string ServiceClientAccountUserId = - "xxx_serviceclient000000001"; // A service account we use to represent outbound calls to 3rd party integrations + public const string + ServiceClientAccountUserId = + "xxx_serviceclient000000001"; // A service account we use to represent outbound calls to 3rd party integrations private static readonly IReadOnlyList ServiceAccounts = new List { diff --git a/src/Domain.Interfaces/Validations/Validation.cs b/src/Domain.Interfaces/Validations/Validation.cs index d4d970d0..d861ca0c 100644 --- a/src/Domain.Interfaces/Validations/Validation.cs +++ b/src/Domain.Interfaces/Validations/Validation.cs @@ -74,13 +74,14 @@ private string Substitute(IDictionary values) } var expression = Expression!; - values.ToList().ForEach(val => - { - if (Substitutions is not null && Substitutions.Contains(val.Key)) + values.ToList() + .ForEach(val => { - expression = expression.Replace(val.Key, val.Value); - } - }); + if (Substitutions is not null && Substitutions.Contains(val.Key)) + { + expression = expression.Replace(val.Key, val.Value); + } + }); return expression; } @@ -91,15 +92,16 @@ private IDictionary InitializeSubstitutions(IEnumerable var substitutions = Substitutions?.ToList() ?? new List(); var counter = 0; - values.ToList().ForEach(val => - { - if (substitutions.Count > counter) + values.ToList() + .ForEach(val => { - result.Add(substitutions[counter], val); + if (substitutions.Count > counter) + { + result.Add(substitutions[counter], val); - counter++; - } - }); + counter++; + } + }); return result; } diff --git a/src/Infrastructure.WebApi.Common.IntegrationTests/ApiContentNegotiationSpec.cs b/src/Infrastructure.WebApi.Common.IntegrationTests/ApiContentNegotiationSpec.cs index dce09fdb..32a6deb5 100644 --- a/src/Infrastructure.WebApi.Common.IntegrationTests/ApiContentNegotiationSpec.cs +++ b/src/Infrastructure.WebApi.Common.IntegrationTests/ApiContentNegotiationSpec.cs @@ -21,8 +21,10 @@ public async Task WhenGetWithNoAccept_ThenReturnsJsonResponse() var result = await Api.GetAsync("testingonly/negotiations/get", request => request.Headers.Remove(HttpHeaders.Accept)); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -31,8 +33,10 @@ public async Task WhenGetWithAcceptForUnsupported_ThenReturns415() var result = await Api.GetAsync("/testingonly/negotiations/get", request => request.Headers.Add(HttpHeaders.Accept, "application/unsupported")); - result.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); - result.Content.Should().BeEmpty(); + result.StatusCode.Should() + .Be(HttpStatusCode.UnsupportedMediaType); + result.Content.Should() + .BeEmpty(); } [Fact] @@ -41,8 +45,10 @@ public async Task WhenGetWithAcceptForJson_ThenReturnsJsonResponse() var result = await Api.GetAsync("/testingonly/negotiations/get", request => request.Headers.Add(HttpHeaders.Accept, HttpContentTypes.Json)); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -51,10 +57,12 @@ public async Task WhenGetWithAcceptForXml_ThenReturnsXmlResponse() var result = await Api.GetAsync("/testingonly/negotiations/get", request => request.Headers.Add(HttpHeaders.Accept, HttpContentTypes.Xml)); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Content.Should().Be("" + - "" + - "amessage" + ""); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Content.Should() + .Be("" + + "" + + "amessage" + ""); } [Fact] @@ -62,8 +70,10 @@ public async Task WhenGetWithNoFormat_ThenReturnsJsonResponse() { var result = await Api.GetAsync("/testingonly/negotiations/get"); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -71,8 +81,10 @@ public async Task WhenGetWithFormatForUnsupported_ThenReturns415() { var result = await Api.GetAsync("/testingonly/negotiations/get?format=unsupported"); - result.StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); - result.Content.Should().BeEmpty(); + result.StatusCode.Should() + .Be(HttpStatusCode.UnsupportedMediaType); + result.Content.Should() + .BeEmpty(); } [Fact] @@ -80,8 +92,10 @@ public async Task WhenGetWithFormatForJson_ThenReturnsJsonResponse() { var result = await Api.GetAsync("/testingonly/negotiations/get?format=json"); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -89,10 +103,12 @@ public async Task WhenGetWithFormatForXml_ThenReturnsXmlResponse() { var result = await Api.GetAsync("/testingonly/negotiations/get?format=xml"); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Content.Should().Be("" + - "" + - "amessage" + ""); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Content.Should() + .Be("" + + "" + + "amessage" + ""); } } #endif \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common.IntegrationTests/ApiDataFormatsSpec.cs b/src/Infrastructure.WebApi.Common.IntegrationTests/ApiDataFormatsSpec.cs index 0a52b917..70533201 100644 --- a/src/Infrastructure.WebApi.Common.IntegrationTests/ApiDataFormatsSpec.cs +++ b/src/Infrastructure.WebApi.Common.IntegrationTests/ApiDataFormatsSpec.cs @@ -41,10 +41,11 @@ public async Task WhenPostWithDifferentDataTypesForJson_ThenReturnsValues() var result = await Api.PostAsync("/testingonly/formats/roundtrip", new StringContent(request, Encoding.UTF8, HttpContentTypes.Json)); - result.Content.Should().Be("{" + "\"custom\":" + "{" + "\"double\":91.1," + "\"enum\":\"twentyOne\"," + - "\"integer\":91," + "\"string\":\"avalue2\"," + $"\"time\":\"{time2.ToIso8601()}\"" + - "}," + "\"double\":99.9," + "\"enum\":\"oneHundredAndOne\"," + "\"integer\":9," + - "\"string\":\"avalue1\"," + $"\"time\":\"{time1.ToIso8601()}\"" + "}"); + result.Content.Should() + .Be("{" + "\"custom\":" + "{" + "\"double\":91.1," + "\"enum\":\"twentyOne\"," + "\"integer\":91," + + "\"string\":\"avalue2\"," + $"\"time\":\"{time2.ToIso8601()}\"" + "}," + "\"double\":99.9," + + "\"enum\":\"oneHundredAndOne\"," + "\"integer\":9," + "\"string\":\"avalue1\"," + + $"\"time\":\"{time1.ToIso8601()}\"" + "}"); } [Fact] @@ -72,14 +73,13 @@ public async Task WhenPostWithDifferentDataTypesForXml_ThenReturnsValues() var result = await Api.PostAsync("/testingonly/formats/roundtrip?format=xml", new StringContent(request, Encoding.UTF8, HttpContentTypes.Json)); - result.Content.Should().Be("" + - "" + - "" + "91.1" + "TwentyOne" + - "91" + "avalue2" + - $"" + "99.9" + - "OneHundredAndOne" + "9" + - "avalue1" + $"" + - ""); + result.Content.Should() + .Be("" + + "" + + "" + "91.1" + "TwentyOne" + "91" + + "avalue2" + $"" + "99.9" + + "OneHundredAndOne" + "9" + "avalue1" + + $"" + ""); } [Fact] @@ -99,8 +99,9 @@ public async Task WhenPostWithIso8601DateTime_ThenReturnsUnixTimestamp() var result = await Api.PostAsync("/testingonly/formats/roundtrip", new StringContent(request, Encoding.UTF8, HttpContentTypes.Json)); - result.Content.Should().Be("{" + "\"custom\":" + "{" + $"\"time\":\"{time2.ToIso8601()}\"" + "}," + - $"\"time\":\"{time1.ToIso8601()}\"" + "}"); + result.Content.Should() + .Be("{" + "\"custom\":" + "{" + $"\"time\":\"{time2.ToIso8601()}\"" + "}," + + $"\"time\":\"{time1.ToIso8601()}\"" + "}"); } [Fact] @@ -120,8 +121,9 @@ public async Task WhenPostWithUnixSecondsDateTime_ThenReturnsUnixTimestamp() var result = await Api.PostAsync("/testingonly/formats/roundtrip", new StringContent(request, Encoding.UTF8, HttpContentTypes.Json)); - result.Content.Should().Be("{" + "\"custom\":" + "{" + $"\"time\":\"{time2.ToIso8601()}\"" + "}," + - $"\"time\":\"{time1.ToIso8601()}\"" + "}"); + result.Content.Should() + .Be("{" + "\"custom\":" + "{" + $"\"time\":\"{time2.ToIso8601()}\"" + "}," + + $"\"time\":\"{time1.ToIso8601()}\"" + "}"); } [Fact] @@ -139,8 +141,8 @@ public async Task WhenPostWithLowercaseEnum_ThenReturnsCamelcased() var result = await Api.PostAsync("/testingonly/formats/roundtrip", new StringContent(request, Encoding.UTF8, HttpContentTypes.Json)); - result.Content.Should().Be("{" + "\"custom\":" + "{" + "\"enum\":\"twentyOne\"" + "}," + - "\"enum\":\"oneHundredAndOne\"" + "}"); + result.Content.Should() + .Be("{" + "\"custom\":" + "{" + "\"enum\":\"twentyOne\"" + "}," + "\"enum\":\"oneHundredAndOne\"" + "}"); } } #endif \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common.IntegrationTests/ApiDefaultStatusCodeSpec.cs b/src/Infrastructure.WebApi.Common.IntegrationTests/ApiDefaultStatusCodeSpec.cs index 7be5a575..456d36f8 100644 --- a/src/Infrastructure.WebApi.Common.IntegrationTests/ApiDefaultStatusCodeSpec.cs +++ b/src/Infrastructure.WebApi.Common.IntegrationTests/ApiDefaultStatusCodeSpec.cs @@ -20,9 +20,12 @@ public async Task WhenPost_ThenReturnsCreated() { var result = await Api.PostAsync("/testingonly/statuses/post", new StatusesPostTestingOnlyRequest()); - result.StatusCode.Should().Be(HttpStatusCode.Created); - result.Headers.Location.Should().Be("alocation"); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.Created); + result.Headers.Location.Should() + .Be("alocation"); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -31,9 +34,12 @@ public async Task WhenPostWithoutLocation_ThenReturnsOk() var result = await Api.PostAsync("/testingonly/statuses/post2", new StatusesPostWithLocationTestingOnlyRequest()); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Headers.Location.Should().BeNull(); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Headers.Location.Should() + .BeNull(); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -41,8 +47,10 @@ public async Task WhenGet_ThenReturnsOk() { var result = await Api.GetAsync("/testingonly/statuses/get"); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -50,8 +58,10 @@ public async Task WhenSearch_ThenReturnsOk() { var result = await Api.GetAsync("/testingonly/statuses/search"); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -59,8 +69,10 @@ public async Task WhenPut_ThenReturnsAccepted() { var result = await Api.PutAsync("/testingonly/statuses/putpatch", new StatusesPutPatchTestingOnlyRequest()); - result.StatusCode.Should().Be(HttpStatusCode.Accepted); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.Accepted); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -68,8 +80,10 @@ public async Task WhenPatch_ThenReturnsAccepted() { var result = await Api.PatchAsync("/testingonly/statuses/putpatch", new StatusesPutPatchTestingOnlyRequest()); - result.StatusCode.Should().Be(HttpStatusCode.Accepted); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.Accepted); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -77,8 +91,10 @@ public async Task WhenDelete_ThenReturnsNoContent() { var result = await Api.DeleteAsync("/testingonly/statuses/delete"); - result.StatusCode.Should().Be(HttpStatusCode.NoContent); - result.Content.Should().BeEmpty(); + result.StatusCode.Should() + .Be(HttpStatusCode.NoContent); + result.Content.Should() + .BeEmpty(); } } #endif \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common.IntegrationTests/ApiErrorSpec.cs b/src/Infrastructure.WebApi.Common.IntegrationTests/ApiErrorSpec.cs index d9b93f4a..f99ae792 100644 --- a/src/Infrastructure.WebApi.Common.IntegrationTests/ApiErrorSpec.cs +++ b/src/Infrastructure.WebApi.Common.IntegrationTests/ApiErrorSpec.cs @@ -19,7 +19,8 @@ public async Task WhenGetError_ThenReturnsError() { var result = await Api.GetAsync("/testingonly/errors/error"); - result.StatusCode.Should().Be(HttpStatusCode.Conflict); + result.StatusCode.Should() + .Be(HttpStatusCode.Conflict); } [Fact] @@ -27,12 +28,14 @@ public async Task WhenGetThrowsException_ThenReturnsServerError() { var result = await Api.GetAsync("/testingonly/errors/throws"); - result.StatusCode.Should().Be(HttpStatusCode.InternalServerError); - result.Content.Should().StartWith("{\"" + "type\":\"https://tools.ietf.org/html/rfc7231#section-6.6.1\"," + - "\"title\":\"An unexpected error occurred\"," + "\"status\":500," + - "\"detail\":\"amessage\"," + - "\"instance\":\"http://localhost/testingonly/errors/throws\"," + - "\"exception\":\"System.InvalidOperationException: amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.InternalServerError); + result.Content.Should() + .StartWith("{\"" + "type\":\"https://tools.ietf.org/html/rfc7231#section-6.6.1\"," + + "\"title\":\"An unexpected error occurred\"," + "\"status\":500," + + "\"detail\":\"amessage\"," + + "\"instance\":\"http://localhost/testingonly/errors/throws\"," + + "\"exception\":\"System.InvalidOperationException: amessage"); } } #endif \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common.IntegrationTests/ApiValidationSpec.cs b/src/Infrastructure.WebApi.Common.IntegrationTests/ApiValidationSpec.cs index 5881c1b4..abd78e3e 100644 --- a/src/Infrastructure.WebApi.Common.IntegrationTests/ApiValidationSpec.cs +++ b/src/Infrastructure.WebApi.Common.IntegrationTests/ApiValidationSpec.cs @@ -20,8 +20,10 @@ public async Task WhenGetUnvalidatedRequest_ThenReturns200() { var result = await Api.GetAsync("/testingonly/validations/unvalidated"); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Content.Message.Should().Be("amessage"); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Content.Message.Should() + .Be("amessage"); } [Fact] @@ -29,13 +31,14 @@ public async Task WhenGetValidatedRequestWithInvalidFields_ThenReturnsValidation { var result = await Api.GetAsync("/testingonly/validations/validated/1234"); - result.StatusCode.Should().Be(HttpStatusCode.BadRequest); - result.Content.Should().Be("{" + "\"type\":\"NotEmptyValidator\"," + "\"title\":\"Validation Error\"," + - "\"status\":400," + "\"detail\":\"'Field1' must not be empty.\"," + - "\"instance\":\"http://localhost/testingonly/validations/validated/1234\"," + - "\"errors\":[" + - "{\"rule\":\"NotEmptyValidator\",\"reason\":\"'Field1' must not be empty.\"}," + - "{\"rule\":\"NotEmptyValidator\",\"reason\":\"'Field2' must not be empty.\"}]}"); + result.StatusCode.Should() + .Be(HttpStatusCode.BadRequest); + result.Content.Should() + .Be("{" + "\"type\":\"NotEmptyValidator\"," + "\"title\":\"Validation Error\"," + "\"status\":400," + + "\"detail\":\"'Field1' must not be empty.\"," + + "\"instance\":\"http://localhost/testingonly/validations/validated/1234\"," + "\"errors\":[" + + "{\"rule\":\"NotEmptyValidator\",\"reason\":\"'Field1' must not be empty.\"}," + + "{\"rule\":\"NotEmptyValidator\",\"reason\":\"'Field2' must not be empty.\"}]}"); } [Fact] @@ -45,8 +48,10 @@ public async Task WhenGetValidatedRequestWithValidId_ThenReturnsResponse() await Api.GetAsync( "/testingonly/validations/validated/1234?Field1=123&Field2=456"); - result.StatusCode.Should().Be(HttpStatusCode.OK); - result.Content.Message.Should().Be("amessage123"); + result.StatusCode.Should() + .Be(HttpStatusCode.OK); + result.Content.Message.Should() + .Be("amessage123"); } } #endif \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common.UnitTests/ContentNegotiationFilterSpec.cs b/src/Infrastructure.WebApi.Common.UnitTests/ContentNegotiationFilterSpec.cs index ac2e9734..75f074ba 100644 --- a/src/Infrastructure.WebApi.Common.UnitTests/ContentNegotiationFilterSpec.cs +++ b/src/Infrastructure.WebApi.Common.UnitTests/ContentNegotiationFilterSpec.cs @@ -29,7 +29,8 @@ public void WhenInvokeAsyncWithNullResponse_ThenReturnsNull() var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeNull(); + result.Result.Should() + .BeNull(); } [Fact] @@ -42,10 +43,17 @@ public void WhenInvokeAsyncWithNakedObjectResponse_ThenReturnsJsonContentAsOk() var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeOfType>(); - result.Result.As>().ContentType.Should().BeNull(); - result.Result.As>().StatusCode.Should().Be((int)HttpStatusCode.OK); - result.Result.As>().Value.Should().Be(response); + result.Result.Should() + .BeOfType>(); + result.Result.As>() + .ContentType.Should() + .BeNull(); + result.Result.As>() + .StatusCode.Should() + .Be((int)HttpStatusCode.OK); + result.Result.As>() + .Value.Should() + .Be(response); } [Fact] @@ -58,8 +66,11 @@ public void WhenInvokeAsyncWithNakedEmptyStringResponse_ThenReturnsJsonContentAs var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeOfType(); - result.Result.As().StatusCode.Should().Be((int)HttpStatusCode.NoContent); + result.Result.Should() + .BeOfType(); + result.Result.As() + .StatusCode.Should() + .Be((int)HttpStatusCode.NoContent); } [Fact] @@ -73,10 +84,17 @@ public void WhenInvokeAsyncWithIValueHttpResultResponse_ThenReturnsJsonContentAs var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeOfType>(); - result.Result.As>().ContentType.Should().BeNull(); - result.Result.As>().StatusCode.Should().Be((int)HttpStatusCode.OK); - result.Result.As>().Value.Should().Be(payload); + result.Result.Should() + .BeOfType>(); + result.Result.As>() + .ContentType.Should() + .BeNull(); + result.Result.As>() + .StatusCode.Should() + .Be((int)HttpStatusCode.OK); + result.Result.As>() + .Value.Should() + .Be(payload); } [Fact] @@ -90,9 +108,14 @@ public void WhenInvokeAsyncWithStreamResultResponse_ThenReturnsJsonContentAsOk() var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeOfType(); - result.Result.As().ContentType.Should().Be(HttpContentTypes.OctetStream); - result.Result.As().FileStream.Should().BeSameAs(stream); + result.Result.Should() + .BeOfType(); + result.Result.As() + .ContentType.Should() + .Be(HttpContentTypes.OctetStream); + result.Result.As() + .FileStream.Should() + .BeSameAs(stream); } [Fact] @@ -105,8 +128,11 @@ public void WhenInvokeAsyncWithNoContentResponse_ThenReturnsJsonContentAsOk() var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeOfType(); - result.Result.As().StatusCode.Should().Be((int)HttpStatusCode.NoContent); + result.Result.Should() + .BeOfType(); + result.Result.As() + .StatusCode.Should() + .Be((int)HttpStatusCode.NoContent); } [Fact] @@ -119,8 +145,11 @@ public void WhenInvokeAsyncWithOtherEmptyIResultResponse_ThenReturnsJsonContentA var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeOfType(); - result.Result.As().StatusCode.Should().Be((int)HttpStatusCode.OK); + result.Result.Should() + .BeOfType(); + result.Result.As() + .StatusCode.Should() + .Be((int)HttpStatusCode.OK); } [Fact] @@ -133,8 +162,11 @@ public void WhenInvokeAsyncWithNullValueIResultResponse_ThenReturnsJsonContentAs var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeOfType>(); - result.Result.As>().StatusCode.Should().Be(200); + result.Result.Should() + .BeOfType>(); + result.Result.As>() + .StatusCode.Should() + .Be(200); } [Fact] @@ -147,10 +179,17 @@ public void WhenInvokeAsyncWithNakedObjectResponseAndAcceptXml_ThenReturnsXml() var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeOfType>(); - result.Result.As>().ContentType.Should().Be(HttpContentTypes.XmlWithCharset); - result.Result.As>().StatusCode.Should().Be((int)HttpStatusCode.OK); - result.Result.As>().Value.Should().Be(response); + result.Result.Should() + .BeOfType>(); + result.Result.As>() + .ContentType.Should() + .Be(HttpContentTypes.XmlWithCharset); + result.Result.As>() + .StatusCode.Should() + .Be((int)HttpStatusCode.OK); + result.Result.As>() + .Value.Should() + .Be(response); } [Fact] @@ -163,10 +202,17 @@ public void WhenInvokeAsyncWithNakedObjectResponseAndFormatXml_ThenReturnsXml() var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeOfType>(); - result.Result.As>().ContentType.Should().Be(HttpContentTypes.XmlWithCharset); - result.Result.As>().StatusCode.Should().Be((int)HttpStatusCode.OK); - result.Result.As>().Value.Should().Be(response); + result.Result.Should() + .BeOfType>(); + result.Result.As>() + .ContentType.Should() + .Be(HttpContentTypes.XmlWithCharset); + result.Result.As>() + .StatusCode.Should() + .Be((int)HttpStatusCode.OK); + result.Result.As>() + .Value.Should() + .Be(response); } [Fact] @@ -180,10 +226,17 @@ public void WhenInvokeAsyncWithIResultResponseAndFormatXml_ThenReturnsXml() var result = _filter.InvokeAsync(context, next); - result.Result.Should().BeOfType>(); - result.Result.As>().ContentType.Should().Be(HttpContentTypes.XmlWithCharset); - result.Result.As>().StatusCode.Should().Be((int)HttpStatusCode.OK); - result.Result.As>().Value.Should().Be(payload); + result.Result.Should() + .BeOfType>(); + result.Result.As>() + .ContentType.Should() + .Be(HttpContentTypes.XmlWithCharset); + result.Result.As>() + .StatusCode.Should() + .Be((int)HttpStatusCode.OK); + result.Result.As>() + .Value.Should() + .Be(payload); } private Mock SetupHttpContext(string? accept = null, string? format = null) @@ -211,7 +264,8 @@ private Mock SetupHttpContext(string? accept = null, string? format var httpContext = new Mock(); httpContext.Setup(hc => hc.RequestServices.GetService(It.IsAny())) .Returns(jsonOptions.Object); - httpContext.Setup(hc => hc.Request).Returns(httpRequest.Object); + httpContext.Setup(hc => hc.Request) + .Returns(httpRequest.Object); return httpContext; } diff --git a/src/Infrastructure.WebApi.Common.UnitTests/HasGetOptionsExtensionsSpec.cs b/src/Infrastructure.WebApi.Common.UnitTests/HasGetOptionsExtensionsSpec.cs index aa19ae69..e8ef6d29 100644 --- a/src/Infrastructure.WebApi.Common.UnitTests/HasGetOptionsExtensionsSpec.cs +++ b/src/Infrastructure.WebApi.Common.UnitTests/HasGetOptionsExtensionsSpec.cs @@ -19,7 +19,8 @@ public void WhenToGetOptionsAndNullOptions_ThenReturnsNull() { var result = ((GetOptionsDto)null!).ToGetOptions(); - result.Should().BeEquivalentTo(new GetOptions()); + result.Should() + .BeEquivalentTo(new GetOptions()); } [Fact] @@ -32,8 +33,11 @@ public void WhenToGetOptionsAndEmbedIsUndefinedAndIsSearchOptions_ThenReturnsExp var result = searchOptions.ToGetOptions(); - result.Expand.Should().Be(ExpandOptions.None); - result.ResourceReferences.Count().Should().Be(0); + result.Expand.Should() + .Be(ExpandOptions.None); + result.ResourceReferences.Count() + .Should() + .Be(0); } [Fact] @@ -43,8 +47,11 @@ public void WhenToGetOptionsAndEmbedIsUndefined_ThenReturnsExpandAll() var result = _hasGetOptions.ToGetOptions(); - result.Expand.Should().Be(ExpandOptions.All); - result.ResourceReferences.Count().Should().Be(0); + result.Expand.Should() + .Be(ExpandOptions.All); + result.ResourceReferences.Count() + .Should() + .Be(0); } [Fact] @@ -54,8 +61,11 @@ public void WhenToGetOptionsAndEmbedIsOff_ThenReturnsDisabled() var result = _hasGetOptions.ToGetOptions(); - result.Expand.Should().Be(ExpandOptions.None); - result.ResourceReferences.Count().Should().Be(0); + result.Expand.Should() + .Be(ExpandOptions.None); + result.ResourceReferences.Count() + .Should() + .Be(0); } [Fact] @@ -65,8 +75,11 @@ public void WhenToGetOptionsAndEmbedIsAll_ThenReturnsEnabled() var result = _hasGetOptions.ToGetOptions(); - result.Expand.Should().Be(ExpandOptions.All); - result.ResourceReferences.Count().Should().Be(0); + result.Expand.Should() + .Be(ExpandOptions.All); + result.ResourceReferences.Count() + .Should() + .Be(0); } [Fact] @@ -76,10 +89,19 @@ public void WhenToGetOptionsAndEmbedIsCommaDelimitedResourceReferences_ThenRetur var result = _hasGetOptions.ToGetOptions(); - result.Expand.Should().Be(ExpandOptions.Custom); - result.ResourceReferences.Count().Should().Be(3); - result.ResourceReferences.ToList()[0].Should().Be("aresourceref1"); - result.ResourceReferences.ToList()[1].Should().Be("aresourceref2"); - result.ResourceReferences.ToList()[2].Should().Be("aresourceref3"); + result.Expand.Should() + .Be(ExpandOptions.Custom); + result.ResourceReferences.Count() + .Should() + .Be(3); + result.ResourceReferences.ToList()[0] + .Should() + .Be("aresourceref1"); + result.ResourceReferences.ToList()[1] + .Should() + .Be("aresourceref2"); + result.ResourceReferences.ToList()[2] + .Should() + .Be("aresourceref3"); } } \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common.UnitTests/HasGetOptionsSpec.cs b/src/Infrastructure.WebApi.Common.UnitTests/HasGetOptionsSpec.cs index c5a9dd8a..3726a5c2 100644 --- a/src/Infrastructure.WebApi.Common.UnitTests/HasGetOptionsSpec.cs +++ b/src/Infrastructure.WebApi.Common.UnitTests/HasGetOptionsSpec.cs @@ -14,7 +14,8 @@ public void WhenAll_ThenReturnsAll() { var result = HasGetOptions.All.ToGetOptions(); - result.Expand.Should().Be(ExpandOptions.All); + result.Expand.Should() + .Be(ExpandOptions.All); } [Fact] @@ -22,28 +23,43 @@ public void WhenNone_ThenReturnsNone() { var result = HasGetOptions.None.ToGetOptions(); - result.Expand.Should().Be(ExpandOptions.None); + result.Expand.Should() + .Be(ExpandOptions.None); } [Fact] public void WhenCustomWithSingleResourceReference_ThenReturnsChildResources() { - var result = HasGetOptions.Custom(x => x.AProperty1).ToGetOptions(); + var result = HasGetOptions.Custom(x => x.AProperty1) + .ToGetOptions(); - result.Expand.Should().Be(ExpandOptions.Custom); - result.ResourceReferences.Count().Should().Be(1); - result.ResourceReferences.ToList()[0].Should().Be("testresource.aproperty1"); + result.Expand.Should() + .Be(ExpandOptions.Custom); + result.ResourceReferences.Count() + .Should() + .Be(1); + result.ResourceReferences.ToList()[0] + .Should() + .Be("testresource.aproperty1"); } [Fact] public void WhenCustomWithMultipleResourceReferences_ThenReturnsChildResources() { - var result = HasGetOptions.Custom(x => x.AProperty1, x => x.AProperty2).ToGetOptions(); + var result = HasGetOptions.Custom(x => x.AProperty1, x => x.AProperty2) + .ToGetOptions(); - result.Expand.Should().Be(ExpandOptions.Custom); - result.ResourceReferences.Count().Should().Be(2); - result.ResourceReferences.ToList()[0].Should().Be("testresource.aproperty1"); - result.ResourceReferences.ToList()[1].Should().Be("testresource.aproperty2"); + result.Expand.Should() + .Be(ExpandOptions.Custom); + result.ResourceReferences.Count() + .Should() + .Be(2); + result.ResourceReferences.ToList()[0] + .Should() + .Be("testresource.aproperty1"); + result.ResourceReferences.ToList()[1] + .Should() + .Be("testresource.aproperty2"); } } diff --git a/src/Infrastructure.WebApi.Common.UnitTests/HasSearchOptionsExtensionsSpec.cs b/src/Infrastructure.WebApi.Common.UnitTests/HasSearchOptionsExtensionsSpec.cs index 9bb117bf..980e6d61 100644 --- a/src/Infrastructure.WebApi.Common.UnitTests/HasSearchOptionsExtensionsSpec.cs +++ b/src/Infrastructure.WebApi.Common.UnitTests/HasSearchOptionsExtensionsSpec.cs @@ -20,7 +20,8 @@ public void WhenToSearchOptionsAndNullOptions_ThenReturnsNull() { var result = ((SearchOptionsDto)null!).ToSearchOptions(); - result.Should().BeEquivalentTo(new SearchOptions()); + result.Should() + .BeEquivalentTo(new SearchOptions()); } [Fact] @@ -28,10 +29,14 @@ public void WhenToSearchOptionsAndAllUndefined_ThenReturnsSearchOptions() { var result = _hasSearchOptions.ToSearchOptions(); - result.Limit.Should().Be(SearchOptions.DefaultLimit); - result.Offset.Should().Be(SearchOptions.NoOffset); - result.Sort.HasValue.Should().BeFalse(); - result.Filter.Fields.Count.Should().Be(0); + result.Limit.Should() + .Be(SearchOptions.DefaultLimit); + result.Offset.Should() + .Be(SearchOptions.NoOffset); + result.Sort.HasValue.Should() + .BeFalse(); + result.Filter.Fields.Count.Should() + .Be(0); } [Fact] @@ -42,10 +47,14 @@ public void WhenToSearchOptionsAndLimit_ThenReturnsSearchOptions() var result = _hasSearchOptions.ToSearchOptions(); - result.Limit.Should().Be(9); - result.Offset.Should().Be(99); - result.Sort.HasValue.Should().BeFalse(); - result.Filter.Fields.Count.Should().Be(0); + result.Limit.Should() + .Be(9); + result.Offset.Should() + .Be(99); + result.Sort.HasValue.Should() + .BeFalse(); + result.Filter.Fields.Count.Should() + .Be(0); } [Fact] @@ -56,10 +65,14 @@ public void WhenToSearchOptionsAndNoLimit_ThenReturnsSearchOptions() var result = _hasSearchOptions.ToSearchOptions(); - result.Limit.Should().Be(SearchOptions.DefaultLimit); - result.Offset.Should().Be(99); - result.Sort.HasValue.Should().BeFalse(); - result.Filter.Fields.Count.Should().Be(0); + result.Limit.Should() + .Be(SearchOptions.DefaultLimit); + result.Offset.Should() + .Be(99); + result.Sort.HasValue.Should() + .BeFalse(); + result.Filter.Fields.Count.Should() + .Be(0); } [Fact] @@ -69,15 +82,19 @@ public void WhenToSearchOptionsAndSingleSort_ThenReturnsSearchOptions() var result = _hasSearchOptions.ToSearchOptions(); - result.Sort.Value.By.Should().Be("Field1"); - result.Sort.Value.Direction.Should().Be(SortDirection.Ascending); + result.Sort.Value.By.Should() + .Be("Field1"); + result.Sort.Value.Direction.Should() + .Be(SortDirection.Ascending); _hasSearchOptions.Sort = "-Field1"; result = _hasSearchOptions.ToSearchOptions(); - result.Sort.Value.By.Should().Be("Field1"); - result.Sort.Value.Direction.Should().Be(SortDirection.Descending); + result.Sort.Value.By.Should() + .Be("Field1"); + result.Sort.Value.Direction.Should() + .Be(SortDirection.Descending); } [Fact] @@ -87,9 +104,14 @@ public void WhenToSearchOptionsAndFilters_ThenReturnsSearchOptions() var result = _hasSearchOptions.ToSearchOptions(); - result.Filter.Fields.Count.Should().Be(2); - result.Filter.Fields[0].Should().Be("Field1"); - result.Filter.Fields[1].Should().Be("Field2"); + result.Filter.Fields.Count.Should() + .Be(2); + result.Filter.Fields[0] + .Should() + .Be("Field1"); + result.Filter.Fields[1] + .Should() + .Be("Field2"); } [Fact] @@ -97,12 +119,19 @@ public void WhenToSearchOptionsAndAllUndefinedWithDefaults_ThenReturnsSearchOpti { var result = _hasSearchOptions.ToSearchOptions(9, 99, "-asort", "afilter"); - result.Limit.Should().Be(9); - result.Offset.Should().Be(99); - result.Sort.Value.By.Should().Be("asort"); - result.Sort.Value.Direction.Should().Be(SortDirection.Descending); - result.Filter.Fields.Count.Should().Be(1); - result.Filter.Fields[0].Should().Be("afilter"); + result.Limit.Should() + .Be(9); + result.Offset.Should() + .Be(99); + result.Sort.Value.By.Should() + .Be("asort"); + result.Sort.Value.Direction.Should() + .Be(SortDirection.Descending); + result.Filter.Fields.Count.Should() + .Be(1); + result.Filter.Fields[0] + .Should() + .Be("afilter"); } [Fact] @@ -110,12 +139,19 @@ public void WhenToSearchOptionsAndAllUndefinedWithDefaultMaxLimit_ThenReturnsSea { var result = _hasSearchOptions.ToSearchOptions(0, 99, "-asort", "afilter"); - result.Limit.Should().Be(SearchOptions.DefaultLimit); - result.Offset.Should().Be(99); - result.Sort.Value.By.Should().Be("asort"); - result.Sort.Value.Direction.Should().Be(SortDirection.Descending); - result.Filter.Fields.Count.Should().Be(1); - result.Filter.Fields[0].Should().Be("afilter"); + result.Limit.Should() + .Be(SearchOptions.DefaultLimit); + result.Offset.Should() + .Be(99); + result.Sort.Value.By.Should() + .Be("asort"); + result.Sort.Value.Direction.Should() + .Be(SortDirection.Descending); + result.Filter.Fields.Count.Should() + .Be(1); + result.Filter.Fields[0] + .Should() + .Be("afilter"); } [Fact] @@ -128,12 +164,19 @@ public void WhenToSearchOptionsWithDefaults_ThenReturnsSearchOptions() var result = _hasSearchOptions.ToSearchOptions(9, 99, "asort2", "afilter2"); - result.Limit.Should().Be(6); - result.Offset.Should().Be(66); - result.Sort.Value.By.Should().Be("asort1"); - result.Sort.Value.Direction.Should().Be(SortDirection.Descending); - result.Filter.Fields.Count.Should().Be(1); - result.Filter.Fields[0].Should().Be("afilter1"); + result.Limit.Should() + .Be(6); + result.Offset.Should() + .Be(66); + result.Sort.Value.By.Should() + .Be("asort1"); + result.Sort.Value.Direction.Should() + .Be(SortDirection.Descending); + result.Filter.Fields.Count.Should() + .Be(1); + result.Filter.Fields[0] + .Should() + .Be("afilter1"); } } diff --git a/src/Infrastructure.WebApi.Common.UnitTests/JsonDateTimeConverterSpec.cs b/src/Infrastructure.WebApi.Common.UnitTests/JsonDateTimeConverterSpec.cs index 1691e8eb..c5207828 100644 --- a/src/Infrastructure.WebApi.Common.UnitTests/JsonDateTimeConverterSpec.cs +++ b/src/Infrastructure.WebApi.Common.UnitTests/JsonDateTimeConverterSpec.cs @@ -19,7 +19,8 @@ public void WhenReadAndIsNeitherStringNorNumber_ThenReturnsMinDate() var result = _converter.Read(ref reader, typeof(DateTime), JsonSerializerOptions.Default); - result.Should().Be(DateTime.MinValue); + result.Should() + .Be(DateTime.MinValue); } [Fact] @@ -30,7 +31,8 @@ public void WhenReadAndIsStringWithInvalidDate_ThenReturnsMinDate() var result = _converter.Read(ref reader, typeof(DateTime), JsonSerializerOptions.Default); - result.Should().Be(DateTime.MinValue); + result.Should() + .Be(DateTime.MinValue); } [Fact] @@ -42,7 +44,8 @@ public void WhenReadAndIsStringAsISO8601Date_ThenReturnsDate() var result = _converter.Read(ref reader, typeof(DateTime), JsonSerializerOptions.Default); - result.Should().Be(now); + result.Should() + .Be(now); } [Fact] @@ -54,7 +57,8 @@ public void WhenReadAndIsNumberAsUnixTimestamp_ThenReturnsDate() var result = _converter.Read(ref reader, typeof(DateTime), JsonSerializerOptions.Default); - result.Should().Be(now); + result.Should() + .Be(now); } [Fact] @@ -71,7 +75,8 @@ public void WhenWriteAndUnixTimestampFormat_ThenWriteUnixTimestamp() stream.Seek(0, SeekOrigin.Begin); var result = new StreamReader(stream).ReadToEnd(); - result.Should().Be($"{now.ToUnixSeconds()}"); + result.Should() + .Be($"{now.ToUnixSeconds()}"); } [Fact] @@ -88,6 +93,7 @@ public void WhenWriteAndIso8601Format_ThenWriteUnixTimestamp() stream.Seek(0, SeekOrigin.Begin); var result = new StreamReader(stream).ReadToEnd(); - result.Should().Be($"\"{now.ToIso8601()}\""); + result.Should() + .Be($"\"{now.ToIso8601()}\""); } } \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common.UnitTests/ServiceCollectionExtensionsSpec.cs b/src/Infrastructure.WebApi.Common.UnitTests/ServiceCollectionExtensionsSpec.cs index 809c52a8..bca3d185 100644 --- a/src/Infrastructure.WebApi.Common.UnitTests/ServiceCollectionExtensionsSpec.cs +++ b/src/Infrastructure.WebApi.Common.UnitTests/ServiceCollectionExtensionsSpec.cs @@ -18,7 +18,8 @@ public void WhenRegisterValidators_ThenRegistersInContainer() services.RegisterValidators(new[] { typeof(ServiceCollectionExtensionsSpec).Assembly }, out _); - services.Should().ContainSingle(service => service.ImplementationType == typeof(TestRequestValidator)); + services.Should() + .ContainSingle(service => service.ImplementationType == typeof(TestRequestValidator)); } [Fact] @@ -29,10 +30,10 @@ public void WhenAddValidatorBehaviorsAndNoRegisteredValidators_ThenRegistersNoBe configuration.AddValidatorBehaviors(Enumerable.Empty(), assemblies); - configuration.BehaviorsToRegister.Should().BeEmpty(); + configuration.BehaviorsToRegister.Should() + .BeEmpty(); } - [Fact] public void WhenAddValidatorBehaviorsAndNoRequestTypes_ThenRegistersNoBehaviors() { @@ -41,10 +42,10 @@ public void WhenAddValidatorBehaviorsAndNoRequestTypes_ThenRegistersNoBehaviors( configuration.AddValidatorBehaviors(validators, Enumerable.Empty()); - configuration.BehaviorsToRegister.Should().BeEmpty(); + configuration.BehaviorsToRegister.Should() + .BeEmpty(); } - [Fact] public void WhenAddValidatorBehaviorsAndNoMatchingValidators_ThenRegistersNoBehaviors() { @@ -54,7 +55,8 @@ public void WhenAddValidatorBehaviorsAndNoMatchingValidators_ThenRegistersNoBeha configuration.AddValidatorBehaviors(validators, assemblies); - configuration.BehaviorsToRegister.Should().BeEmpty(); + configuration.BehaviorsToRegister.Should() + .BeEmpty(); } [Fact] diff --git a/src/Infrastructure.WebApi.Common.UnitTests/SubDomainModulesSpec.cs b/src/Infrastructure.WebApi.Common.UnitTests/SubDomainModulesSpec.cs index 9224a74b..62de81dd 100644 --- a/src/Infrastructure.WebApi.Common.UnitTests/SubDomainModulesSpec.cs +++ b/src/Infrastructure.WebApi.Common.UnitTests/SubDomainModulesSpec.cs @@ -15,34 +15,34 @@ public class SubDomainModulesSpec [Fact] public void WhenRegisterAndNullModule_ThenThrows() { - _modules - .Invoking(x => x.Register(null!)) - .Should().Throw(); + _modules.Invoking(x => x.Register(null!)) + .Should() + .Throw(); } [Fact] public void WhenRegisterAndNullApiAssembly_ThenThrows() { - _modules - .Invoking(x => x.Register(new TestModule { ApiAssembly = null! })) - .Should().Throw(); + _modules.Invoking(x => x.Register(new TestModule { ApiAssembly = null! })) + .Should() + .Throw(); } [Fact] public void WhenRegisterAndNullAggregatePrefixes_ThenThrows() { - _modules - .Invoking(x => x.Register(new TestModule { AggregatePrefixes = null! })) - .Should().Throw(); + _modules.Invoking(x => x.Register(new TestModule { AggregatePrefixes = null! })) + .Should() + .Throw(); } [Fact] public void WhenRegisterAndNullMinimalApiRegistrationFunction_ThenThrows() { - _modules - .Invoking(x => x.Register(new TestModule + _modules.Invoking(x => x.Register(new TestModule { ApiAssembly = typeof(SubDomainModulesSpec).Assembly, RegisterServicesFunction = (_, _) => { } })) - .Should().Throw(); + .Should() + .Throw(); } [Fact] @@ -55,7 +55,8 @@ public void WhenRegisterAndNullRegisterServicesFunction_ThenRegisters() RegisterServicesFunction = null! }); - _modules.ApiAssemblies.Should().ContainSingle(); + _modules.ApiAssemblies.Should() + .ContainSingle(); } [Fact] @@ -83,7 +84,8 @@ public void WhenRegisterServices_ThenAppliedToAllModules() _modules.RegisterServices(configuration, services); - wasCalled.Should().BeTrue(); + wasCalled.Should() + .BeTrue(); } [Fact] @@ -109,7 +111,8 @@ public void WhenConfigureHost_ThenAppliedToAllModules() _modules.ConfigureHost(app); - wasCalled.Should().BeTrue(); + wasCalled.Should() + .BeTrue(); } } diff --git a/src/Infrastructure.WebApi.Common.UnitTests/Validation/HasGetOptionsValidatorSpec.cs b/src/Infrastructure.WebApi.Common.UnitTests/Validation/HasGetOptionsValidatorSpec.cs index 644c51e2..d7b0a62b 100644 --- a/src/Infrastructure.WebApi.Common.UnitTests/Validation/HasGetOptionsValidatorSpec.cs +++ b/src/Infrastructure.WebApi.Common.UnitTests/Validation/HasGetOptionsValidatorSpec.cs @@ -70,7 +70,9 @@ public void WhenEmbedIsInvalidResourceReference_ThenThrows() { _dto.Embed = "^aresourceref"; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.HasGetOptionsValidator_InvalidEmbed); } @@ -79,7 +81,9 @@ public void WhenEmbedIsInvalidChildResourceReference_ThenThrows() { _dto.Embed = "aresourceref.^achildresourceref"; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.HasGetOptionsValidator_InvalidEmbed); } @@ -88,7 +92,9 @@ public void WhenEmbedIsInvalidGrandChildResourceReference_ThenThrows() { _dto.Embed = "aresourceref.achildresourceref.^agrandchildresourceref"; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.HasGetOptionsValidator_InvalidEmbed); } @@ -98,7 +104,9 @@ public void WhenEmbedContainsTooManyResources_ThenThrows() _dto.Embed = "aresourceref1,aresourceref2,aresourceref3,aresourceref4,aresourceref5,aresourceref6,aresourceref7,aresourceref8,aresourceref9,aresourceref10,aresourceref11"; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.HasGetOptionsValidator_TooManyResourceReferences); } } diff --git a/src/Infrastructure.WebApi.Common.UnitTests/Validation/HasSearchOptionsValidatorSpec.cs b/src/Infrastructure.WebApi.Common.UnitTests/Validation/HasSearchOptionsValidatorSpec.cs index 8fdfb1e0..47fc51ea 100644 --- a/src/Infrastructure.WebApi.Common.UnitTests/Validation/HasSearchOptionsValidatorSpec.cs +++ b/src/Infrastructure.WebApi.Common.UnitTests/Validation/HasSearchOptionsValidatorSpec.cs @@ -61,7 +61,9 @@ public void WhenLimitIsLessThanMin_ThenThrows() { _dto.Limit = SearchOptions.NoLimit - 1; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.HasSearchOptionsValidator_InvalidLimit); } @@ -70,7 +72,9 @@ public void WhenLimitIsGreaterThanMax_ThenThrows() { _dto.Limit = SearchOptions.MaxLimit + 1; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.HasSearchOptionsValidator_InvalidLimit); } @@ -103,7 +107,9 @@ public void WhenOffsetIsLessThanMin_ThenThrows() { _dto.Offset = SearchOptions.NoOffset - 1; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.HasSearchOptionsValidator_InvalidOffset); } @@ -112,7 +118,9 @@ public void WhenOffsetIsGreaterThanMax_ThenThrows() { _dto.Offset = SearchOptions.MaxLimit + 1; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.HasSearchOptionsValidator_InvalidOffset); } @@ -129,7 +137,9 @@ public void WhenSortIsInvalid_ThenThrows() { _dto.Sort = "*"; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.HasSearchOptionsValidator_InvalidSort); } @@ -146,7 +156,9 @@ public void WhenFilterIsInvalid_ThenThrows() { _dto.Filter = "*"; - _validator.Invoking(x => x.ValidateAndThrow(_dto)).Should().Throw() + _validator.Invoking(x => x.ValidateAndThrow(_dto)) + .Should() + .Throw() .WithMessageLike(ValidationResources.HasSearchOptionsValidator_InvalidFilter); } } diff --git a/src/Infrastructure.WebApi.Common.UnitTests/ValidationBehaviorSpec.cs b/src/Infrastructure.WebApi.Common.UnitTests/ValidationBehaviorSpec.cs index 82e20895..f744b54c 100644 --- a/src/Infrastructure.WebApi.Common.UnitTests/ValidationBehaviorSpec.cs +++ b/src/Infrastructure.WebApi.Common.UnitTests/ValidationBehaviorSpec.cs @@ -18,10 +18,14 @@ public ValidationBehaviorSpec() { _validator = new Mock>(); var httpContextAccessor = new Mock(); - httpContextAccessor.Setup(hca => hca.HttpContext!.Request.Scheme).Returns("ascheme"); - httpContextAccessor.Setup(hca => hca.HttpContext!.Request.Host).Returns(new HostString("ahost")); - httpContextAccessor.Setup(hca => hca.HttpContext!.Request.PathBase).Returns(new PathString("/abasepath")); - httpContextAccessor.Setup(hca => hca.HttpContext!.Request.Path).Returns("/apath"); + httpContextAccessor.Setup(hca => hca.HttpContext!.Request.Scheme) + .Returns("ascheme"); + httpContextAccessor.Setup(hca => hca.HttpContext!.Request.Host) + .Returns(new HostString("ahost")); + httpContextAccessor.Setup(hca => hca.HttpContext!.Request.PathBase) + .Returns(new PathString("/abasepath")); + httpContextAccessor.Setup(hca => hca.HttpContext!.Request.Path) + .Returns("/apath"); httpContextAccessor.Setup(hca => hca.HttpContext!.Request.QueryString) .Returns(new QueryString("?aquerystring")); _behavior = new ValidationBehavior(_validator.Object, httpContextAccessor.Object); @@ -41,9 +45,11 @@ public async Task WhenHandleAndValidatorPasses_ThenExecutesMiddleware() return Task.FromResult(Results.Ok()); }, CancellationToken.None); - wasNextCalled.Should().BeTrue(); + wasNextCalled.Should() + .BeTrue(); _validator.Verify(val => val.ValidateAsync(request, CancellationToken.None)); - result.Should().Be(Results.Ok()); + result.Should() + .Be(Results.Ok()); } [Fact] @@ -51,8 +57,7 @@ public async Task WhenHandleAndValidatorFails_ThenReturnsBadRequest() { var request = new TestRequest(); var wasNextCalled = false; - var errors = new ValidationResult(new List - { new("aproperty", "anerror") }); + var errors = new ValidationResult(new List { new("aproperty", "anerror") }); _validator.Setup(val => val.ValidateAsync(It.IsAny(), It.IsAny())) .Returns(Task.FromResult(errors)); @@ -62,7 +67,8 @@ public async Task WhenHandleAndValidatorFails_ThenReturnsBadRequest() return Task.FromResult(Results.Ok()); }, CancellationToken.None); - wasNextCalled.Should().BeFalse(); + wasNextCalled.Should() + .BeFalse(); _validator.Verify(val => val.ValidateAsync(request, CancellationToken.None)); result.Should() .BeEquivalentTo(TypedResults.Problem(errors.ToRfc7807("ascheme://ahost/abasepath/apath?aquerystring"))); diff --git a/src/Infrastructure.WebApi.Common/HandlerExtensions.cs b/src/Infrastructure.WebApi.Common/HandlerExtensions.cs index 6dc7ae32..83b8cd4a 100644 --- a/src/Infrastructure.WebApi.Common/HandlerExtensions.cs +++ b/src/Infrastructure.WebApi.Common/HandlerExtensions.cs @@ -61,8 +61,8 @@ public static IResult HandleApiResult(this ApiResult ((PostResult)response.Value).ToResult(operation), - error => error.ToResult()); + return result() + .Match(response => ((PostResult)response.Value).ToResult(operation), error => error.ToResult()); } /// @@ -72,7 +72,8 @@ public static IResult HandleApiResult(this ApiPostResult response.Value.ToResult(operation), error => error.ToResult()); + return result() + .Match(response => response.Value.ToResult(operation), error => error.ToResult()); } /// @@ -80,12 +81,14 @@ public static IResult HandleApiResult(this ApiPostResult public static IResult HandleApiResult(this ApiEmptyResult result, WebApiOperation operation) { - return result().Match(response => ((PostResult)response.Value).ToResult(operation), - error => error.ToResult()); + return result() + .Match(response => ((PostResult)response.Value).ToResult(operation), + error => error.ToResult()); } /// - /// Converts the in the to an + /// Converts the in the to an + /// /// using the callback /// public static Result, Error> HandleApplicationResult( @@ -97,7 +100,8 @@ public static Result, Error> HandleApplicationResult - /// Converts the in the to an + /// Converts the in the to an + /// /// using the callback /// public static Result HandleApplicationResult( diff --git a/src/Infrastructure.WebApi.Common/HasGetOptions.cs b/src/Infrastructure.WebApi.Common/HasGetOptions.cs index 15434827..fd9e7e58 100644 --- a/src/Infrastructure.WebApi.Common/HasGetOptions.cs +++ b/src/Infrastructure.WebApi.Common/HasGetOptions.cs @@ -19,6 +19,7 @@ public class HasGetOptions : IHasGetOptions public static HasGetOptions Custom(params Expression>[] resourceProperties) { - return GetOptions.Custom(resourceProperties).ToHasGetOptions(); + return GetOptions.Custom(resourceProperties) + .ToHasGetOptions(); } } \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common/HasGetOptionsExtensions.cs b/src/Infrastructure.WebApi.Common/HasGetOptionsExtensions.cs index 3fea0511..9b237e03 100644 --- a/src/Infrastructure.WebApi.Common/HasGetOptionsExtensions.cs +++ b/src/Infrastructure.WebApi.Common/HasGetOptionsExtensions.cs @@ -9,8 +9,8 @@ public static class HasGetOptionsExtensions /// /// Converts a to a /// - public static GetOptions ToGetOptions(this IHasGetOptions requestDto, - ExpandOptions? defaultExpand = null, List? defaultChildResources = null) + public static GetOptions ToGetOptions(this IHasGetOptions requestDto, ExpandOptions? defaultExpand = null, + List? defaultChildResources = null) { if (requestDto.NotExists()) { @@ -45,8 +45,9 @@ public static GetOptions ToGetOptions(this IHasGetOptions requestDto, return GetOptions.All; } - var values = (requestDto.Embed ?? string.Empty) - .Split(GetOptions.EmbedRequestParamDelimiter).Select(value => value.ToLowerInvariant().Trim()) + var values = (requestDto.Embed ?? string.Empty).Split(GetOptions.EmbedRequestParamDelimiter) + .Select(value => value.ToLowerInvariant() + .Trim()) .ToList(); return GetOptions.Custom(values); diff --git a/src/Infrastructure.WebApi.Common/HasSearchOptionsExtensions.cs b/src/Infrastructure.WebApi.Common/HasSearchOptionsExtensions.cs index dc834fb4..de375584 100644 --- a/src/Infrastructure.WebApi.Common/HasSearchOptionsExtensions.cs +++ b/src/Infrastructure.WebApi.Common/HasSearchOptionsExtensions.cs @@ -73,8 +73,9 @@ static int ToLimit(IHasSearchOptions options, int? defaultLimit) private static string ParseSortBy(string sortBy) { - return sortBy.StartsWith(SearchOptions.SortSigns[0].ToString()) || - sortBy.StartsWith(SearchOptions.SortSigns[1].ToString()) + return sortBy.StartsWith(SearchOptions.SortSigns[0] + .ToString()) || sortBy.StartsWith(SearchOptions.SortSigns[1] + .ToString()) ? sortBy.TrimStart(SearchOptions.SortSigns) : sortBy; } @@ -88,6 +89,7 @@ private static SortDirection ParseSortDirection(string sort) private static List ParseFilters(string filter) { - return filter.Split(SearchOptions.FilterDelimiters).ToList(); + return filter.Split(SearchOptions.FilterDelimiters) + .ToList(); } } \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common/HostEnvironmentExtensions.cs b/src/Infrastructure.WebApi.Common/HostEnvironmentExtensions.cs index ef6c7509..4a3b2ede 100644 --- a/src/Infrastructure.WebApi.Common/HostEnvironmentExtensions.cs +++ b/src/Infrastructure.WebApi.Common/HostEnvironmentExtensions.cs @@ -11,7 +11,6 @@ public static bool IsTestingOnly(this IHostEnvironment hostEnvironment) { ArgumentNullException.ThrowIfNull(hostEnvironment); - return hostEnvironment.IsEnvironment(Environments.Development) - || hostEnvironment.IsEnvironment("CI"); + return hostEnvironment.IsEnvironment(Environments.Development) || hostEnvironment.IsEnvironment("CI"); } } \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common/ServiceCollectionExtensions.cs b/src/Infrastructure.WebApi.Common/ServiceCollectionExtensions.cs index 783fe905..bb8debcb 100644 --- a/src/Infrastructure.WebApi.Common/ServiceCollectionExtensions.cs +++ b/src/Infrastructure.WebApi.Common/ServiceCollectionExtensions.cs @@ -16,8 +16,7 @@ public static class ServiceCollectionExtensions /// /// public static MediatRServiceConfiguration AddValidatorBehaviors(this MediatRServiceConfiguration configuration, - IEnumerable registeredValidators, - IEnumerable assembliesContainingApis) + IEnumerable registeredValidators, IEnumerable assembliesContainingApis) { ArgumentNullException.ThrowIfNull(configuration); ArgumentNullException.ThrowIfNull(registeredValidators); @@ -29,8 +28,7 @@ public static MediatRServiceConfiguration AddValidatorBehaviors(this MediatRServ return configuration; } - var serviceClasses = assembliesContainingApis - .SelectMany(assembly => assembly.GetTypes()) + var serviceClasses = assembliesContainingApis.SelectMany(assembly => assembly.GetTypes()) .Where(IsServiceClass); var requestTypes = serviceClasses @@ -75,9 +73,8 @@ public static MediatRServiceConfiguration AddValidatorBehaviors(this MediatRServ return validators.Find(type => { var implementedInterfaces = type.GetInterfaces(); - var validatorInterface = implementedInterfaces - .FirstOrDefault(@interface => @interface.IsGenericType - && @interface.GetGenericTypeDefinition() == typeof(IValidator<>)); + var validatorInterface = implementedInterfaces.FirstOrDefault(@interface => + @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IValidator<>)); if (validatorInterface is not null) { var validatorRequestType = validatorInterface.GenericTypeArguments.FirstOrDefault(); @@ -105,9 +102,8 @@ static bool IsRequestType(Type type) static Type? GetRequestType(Type type) { var interfaces = type.GetInterfaces(); - return interfaces - .FirstOrDefault(@interface => @interface.IsGenericType - && @interface.GetGenericTypeDefinition() == typeof(IWebRequest<>)); + return interfaces.FirstOrDefault(@interface => + @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IWebRequest<>)); } static Type? GetResponseType(Type type) diff --git a/src/Infrastructure.WebApi.Common/Validation/HasGetOptionsValidator.cs b/src/Infrastructure.WebApi.Common/Validation/HasGetOptionsValidator.cs index cb9c379b..8974493f 100644 --- a/src/Infrastructure.WebApi.Common/Validation/HasGetOptionsValidator.cs +++ b/src/Infrastructure.WebApi.Common/Validation/HasGetOptionsValidator.cs @@ -20,10 +20,14 @@ public HasGetOptionsValidator() { When(dto => dto.Embed.HasValue(), () => { - RuleForEach(dto => dto.ToGetOptions(null, null).ResourceReferences).Matches(ResourceReferenceExpression) + RuleForEach(dto => dto.ToGetOptions(null, null) + .ResourceReferences) + .Matches(ResourceReferenceExpression) .WithMessage(ValidationResources.HasGetOptionsValidator_InvalidEmbed); - RuleFor(dto => dto.ToGetOptions(null, null).ResourceReferences.Count()) - .LessThanOrEqualTo(GetOptions.MaxResourceReferences).WithMessage( + RuleFor(dto => dto.ToGetOptions(null, null) + .ResourceReferences.Count()) + .LessThanOrEqualTo(GetOptions.MaxResourceReferences) + .WithMessage( ValidationResources.HasGetOptionsValidator_TooManyResourceReferences.Format(GetOptions .MaxResourceReferences)); }); diff --git a/src/Infrastructure.WebApi.Common/Validation/HasSearchOptionsValidator.cs b/src/Infrastructure.WebApi.Common/Validation/HasSearchOptionsValidator.cs index c9b45b83..0575ee26 100644 --- a/src/Infrastructure.WebApi.Common/Validation/HasSearchOptionsValidator.cs +++ b/src/Infrastructure.WebApi.Common/Validation/HasSearchOptionsValidator.cs @@ -19,18 +19,30 @@ public class HasSearchOptionsValidator : AbstractValidator, I public HasSearchOptionsValidator(IHasGetOptionsValidator hasGetOptionsValidator) { - RuleFor(dto => dto.Limit!.Value).InclusiveBetween(SearchOptions.NoLimit, SearchOptions.MaxLimit) - .When(dto => dto.Limit.HasValue).WithMessage( + RuleFor(dto => dto.Limit!.Value) + .InclusiveBetween(SearchOptions.NoLimit, SearchOptions.MaxLimit) + .When(dto => dto.Limit.HasValue) + .WithMessage( ValidationResources.HasSearchOptionsValidator_InvalidLimit.Format(SearchOptions.NoLimit, - SearchOptions.DefaultLimit)); - RuleFor(dto => dto.Offset!.Value).InclusiveBetween(SearchOptions.NoOffset, SearchOptions.MaxLimit) - .When(dto => dto.Offset.HasValue).WithMessage( + SearchOptions.DefaultLimit)); + RuleFor(dto => dto.Offset!.Value) + .InclusiveBetween(SearchOptions.NoOffset, SearchOptions.MaxLimit) + .When(dto => dto.Offset.HasValue) + .WithMessage( ValidationResources.HasSearchOptionsValidator_InvalidOffset.Format(SearchOptions.NoOffset, - SearchOptions.MaxLimit)); - RuleFor(dto => dto.Sort!).Matches(SortExpression).When(dto => dto.Sort.HasValue()) + SearchOptions.MaxLimit)); + RuleFor(dto => dto.Sort!) + .Matches(SortExpression) + .When(dto => dto.Sort.HasValue()) .WithMessage(ValidationResources.HasSearchOptionsValidator_InvalidSort); - RuleFor(dto => dto.Filter!).Matches(FilterExpression).When(dto => dto.Filter.HasValue()) + RuleFor(dto => dto.Filter!) + .Matches(FilterExpression) + .When(dto => dto.Filter.HasValue()) .WithMessage(ValidationResources.HasSearchOptionsValidator_InvalidFilter); - When(dto => dto.Embed.HasValue(), () => { RuleFor(dto => dto).SetValidator(hasGetOptionsValidator); }); + When(dto => dto.Embed.HasValue(), () => + { + RuleFor(dto => dto) + .SetValidator(hasGetOptionsValidator); + }); } } \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common/ValidationBehavior.cs b/src/Infrastructure.WebApi.Common/ValidationBehavior.cs index 2b97f407..3b7ddb3d 100644 --- a/src/Infrastructure.WebApi.Common/ValidationBehavior.cs +++ b/src/Infrastructure.WebApi.Common/ValidationBehavior.cs @@ -13,13 +13,11 @@ namespace Infrastructure.WebApi.Common; /// [UsedImplicitly] public class ValidationBehavior : IPipelineBehavior - where TRequest : IWebRequest - where TResponse : IWebResponse + where TRequest : IWebRequest where TResponse : IWebResponse { private readonly IHttpContextAccessor _httpContextAccessor; private readonly IValidator _validator; - public ValidationBehavior(IValidator validator, IHttpContextAccessor httpContextAccessor) { _validator = validator; diff --git a/src/Infrastructure.WebApi.Common/ValidationResultExtensions.cs b/src/Infrastructure.WebApi.Common/ValidationResultExtensions.cs index 8273b28f..a1d418f7 100644 --- a/src/Infrastructure.WebApi.Common/ValidationResultExtensions.cs +++ b/src/Infrastructure.WebApi.Common/ValidationResultExtensions.cs @@ -14,13 +14,16 @@ public static class ValidationResultExtensions public static ProblemDetails ToRfc7807(this ValidationResult result, string requestUrl) { var validationDetails = result.Errors.Select(error => new - { - Rule = error.ErrorCode, - Reason = error.ErrorMessage, - Value = error.AttemptedValue - }).ToList(); - var firstMessage = result.Errors.Select(error => error.ErrorMessage).First(); - var firstCode = result.Errors.Select(error => error.ErrorCode).First(); + { + Rule = error.ErrorCode, + Reason = error.ErrorMessage, + Value = error.AttemptedValue + }) + .ToList(); + var firstMessage = result.Errors.Select(error => error.ErrorMessage) + .First(); + var firstCode = result.Errors.Select(error => error.ErrorCode) + .First(); var details = new ProblemDetails { diff --git a/src/Infrastructure.WebApi.Common/WebApplicationExtensions.cs b/src/Infrastructure.WebApi.Common/WebApplicationExtensions.cs index cd460aca..3d39324c 100644 --- a/src/Infrastructure.WebApi.Common/WebApplicationExtensions.cs +++ b/src/Infrastructure.WebApi.Common/WebApplicationExtensions.cs @@ -17,36 +17,35 @@ public static class WebApplicationExtensions /// public static IApplicationBuilder AddExceptionShielding(this WebApplication app) { - return app.UseExceptionHandler(configure => - configure.Run(async context => + return app.UseExceptionHandler(configure => configure.Run(async context => + { + var exceptionMessage = string.Empty; + var exceptionStackTrace = string.Empty; + if (app.Environment.IsTestingOnly()) { - var exceptionMessage = string.Empty; - var exceptionStackTrace = string.Empty; - if (app.Environment.IsTestingOnly()) + var contextFeature = context.Features.Get(); + if (contextFeature is not null) { - var contextFeature = context.Features.Get(); - if (contextFeature is not null) - { - exceptionMessage = contextFeature.Error.Message; - exceptionStackTrace = contextFeature.Error.ToString(); - } - } - - var details = new ProblemDetails - { - Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1", - Title = "An unexpected error occurred", - Status = (int)HttpStatusCode.InternalServerError, - Instance = context.Request.GetDisplayUrl(), - Detail = exceptionMessage - }; - if (exceptionStackTrace.HasValue()) - { - details.Extensions.Add("exception", exceptionStackTrace); + exceptionMessage = contextFeature.Error.Message; + exceptionStackTrace = contextFeature.Error.ToString(); } + } + var details = new ProblemDetails + { + Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1", + Title = "An unexpected error occurred", + Status = (int)HttpStatusCode.InternalServerError, + Instance = context.Request.GetDisplayUrl(), + Detail = exceptionMessage + }; + if (exceptionStackTrace.HasValue()) + { + details.Extensions.Add("exception", exceptionStackTrace); + } - await Results.Problem(details).ExecuteAsync(context); - })); + await Results.Problem(details) + .ExecuteAsync(context); + })); } } \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Common/XmlHttpResult.cs b/src/Infrastructure.WebApi.Common/XmlHttpResult.cs index 9c606cba..7ede0d9a 100644 --- a/src/Infrastructure.WebApi.Common/XmlHttpResult.cs +++ b/src/Infrastructure.WebApi.Common/XmlHttpResult.cs @@ -17,8 +17,7 @@ namespace Infrastructure.WebApi.Common; public sealed class XmlHttpResult : IResult, IStatusCodeHttpResult, IValueHttpResult, IValueHttpResult, IContentTypeHttpResult { - internal XmlHttpResult(TValue? value, int? statusCode, - XmlSerializerOptions? xmlSerializerOptions = null) + internal XmlHttpResult(TValue? value, int? statusCode, XmlSerializerOptions? xmlSerializerOptions = null) { Value = value; ContentType = HttpContentTypes.XmlWithCharset; @@ -68,13 +67,8 @@ public Task ExecuteAsync(HttpContext httpContext) /// internal static partial class MicrosoftAspNetCoreExtensions { - public static Task WriteResultAsXmlAsync( - HttpContext httpContext, - ILogger logger, - T? value, - string? contentType, - XmlSerializerOptions? xmlSerializerOptions - ) + public static Task WriteResultAsXmlAsync(HttpContext httpContext, ILogger logger, T? value, string? contentType, + XmlSerializerOptions? xmlSerializerOptions) { if (value is null) { @@ -88,27 +82,18 @@ public static Task WriteResultAsXmlAsync( // In this case the polymorphism is not // relevant and we don't need to box. - return httpContext.Response.WriteAsXmlAsync( - value, contentType, xmlSerializerOptions); + return httpContext.Response.WriteAsXmlAsync(value, contentType, xmlSerializerOptions); } var runtimeType = value.GetType(); Log.WritingResultAsXml(logger, runtimeType.Name); - return httpContext.Response.WriteAsXmlAsync( - value, - runtimeType, - contentType, - xmlSerializerOptions); + return httpContext.Response.WriteAsXmlAsync(value, runtimeType, contentType, xmlSerializerOptions); } - private static Task WriteAsXmlAsync( - this HttpResponse response, - TValue value, - string? contentType, - XmlSerializerOptions? options, - CancellationToken cancellationToken = default) + private static Task WriteAsXmlAsync(this HttpResponse response, TValue value, string? contentType, + XmlSerializerOptions? options, CancellationToken cancellationToken = default) { if (response == null) { @@ -128,13 +113,8 @@ private static Task WriteAsXmlAsync( return XmlSerializer.SerializeAsync(response.Body, value, options, cancellationToken); } - private static Task WriteAsXmlAsync( - this HttpResponse response, - object? value, - Type type, - string? contentType, - XmlSerializerOptions? options, - CancellationToken cancellationToken = default) + private static Task WriteAsXmlAsync(this HttpResponse response, object? value, Type type, string? contentType, + XmlSerializerOptions? options, CancellationToken cancellationToken = default) { if (response == null) { @@ -153,18 +133,13 @@ private static Task WriteAsXmlAsync( // if no user provided token, pass the RequestAborted token and ignore OperationCanceledException if (!cancellationToken.CanBeCanceled) { - return WriteAsXmlAsyncSlow(response.Body, value, type, options, - response.HttpContext.RequestAborted); + return WriteAsXmlAsyncSlow(response.Body, value, type, options, response.HttpContext.RequestAborted); } return XmlSerializer.SerializeAsync(response.Body, value, type, options, cancellationToken); } - private static async Task WriteAsXmlAsyncSlow( - Stream body, - object? value, - Type type, - XmlSerializerOptions options, + private static async Task WriteAsXmlAsyncSlow(Stream body, object? value, Type type, XmlSerializerOptions options, CancellationToken cancellationToken) { try @@ -176,10 +151,7 @@ private static async Task WriteAsXmlAsyncSlow( } } - private static async Task WriteAsXmlAsyncSlow( - Stream body, - TValue value, - XmlSerializerOptions options, + private static async Task WriteAsXmlAsyncSlow(Stream body, TValue value, XmlSerializerOptions options, CancellationToken cancellationToken) { try @@ -194,8 +166,8 @@ private static async Task WriteAsXmlAsyncSlow( private static XmlSerializerOptions ResolveSerializerOptions(HttpContext httpContext) { // Attempt to resolve options from DI then fallback to default options - return httpContext.RequestServices.GetService>()?.Value.SerializerOptions ?? - XmlOptions.DefaultSerializerOptions; + return httpContext.RequestServices.GetService>() + ?.Value.SerializerOptions ?? XmlOptions.DefaultSerializerOptions; } /// @@ -206,65 +178,26 @@ internal static class ProblemDetailsDefaults { private static readonly Dictionary Defaults = new() { - [400] = - ( - "https://tools.ietf.org/html/rfc7231#section-6.5.1", - "Bad Request" - ), - - [401] = - ( - "https://tools.ietf.org/html/rfc7235#section-3.1", - "Unauthorized" - ), - - [403] = - ( - "https://tools.ietf.org/html/rfc7231#section-6.5.3", - "Forbidden" - ), - - [404] = - ( - "https://tools.ietf.org/html/rfc7231#section-6.5.4", - "Not Found" - ), - - [405] = - ( - "https://tools.ietf.org/html/rfc7231#section-6.5.5", - "Method Not Allowed" - ), - - [406] = - ( - "https://tools.ietf.org/html/rfc7231#section-6.5.6", - "Not Acceptable" - ), - - [409] = - ( - "https://tools.ietf.org/html/rfc7231#section-6.5.8", - "Conflict" - ), - - [415] = - ( - "https://tools.ietf.org/html/rfc7231#section-6.5.13", - "Unsupported Media Type" - ), - - [422] = - ( - "https://tools.ietf.org/html/rfc4918#section-11.2", - "Unprocessable Entity" - ), - - [500] = - ( - "https://tools.ietf.org/html/rfc7231#section-6.6.1", - "An error occurred while processing your request." - ) + [400] = ("https://tools.ietf.org/html/rfc7231#section-6.5.1", "Bad Request"), + + [401] = ("https://tools.ietf.org/html/rfc7235#section-3.1", "Unauthorized"), + + [403] = ("https://tools.ietf.org/html/rfc7231#section-6.5.3", "Forbidden"), + + [404] = ("https://tools.ietf.org/html/rfc7231#section-6.5.4", "Not Found"), + + [405] = ("https://tools.ietf.org/html/rfc7231#section-6.5.5", "Method Not Allowed"), + + [406] = ("https://tools.ietf.org/html/rfc7231#section-6.5.6", "Not Acceptable"), + + [409] = ("https://tools.ietf.org/html/rfc7231#section-6.5.8", "Conflict"), + + [415] = ("https://tools.ietf.org/html/rfc7231#section-6.5.13", "Unsupported Media Type"), + + [422] = ("https://tools.ietf.org/html/rfc4918#section-11.2", "Unprocessable Entity"), + + [500] = ("https://tools.ietf.org/html/rfc7231#section-6.6.1", + "An error occurred while processing your request.") }; public static void Apply(ProblemDetails problemDetails, int? statusCode) @@ -296,8 +229,7 @@ public static void Apply(ProblemDetails problemDetails, int? statusCode) internal static partial class Log { - [LoggerMessage(1, LogLevel.Information, - "Setting HTTP status code {StatusCode}.", + [LoggerMessage(1, LogLevel.Information, "Setting HTTP status code {StatusCode}.", EventName = "WritingResultAsStatusCode")] public static partial void WritingResultAsStatusCode(ILogger logger, int statusCode); diff --git a/src/Infrastructure.WebApi.Generators/Extensions/StringExtensions.cs b/src/Infrastructure.WebApi.Generators/Extensions/StringExtensions.cs index eda36f48..e65169db 100644 --- a/src/Infrastructure.WebApi.Generators/Extensions/StringExtensions.cs +++ b/src/Infrastructure.WebApi.Generators/Extensions/StringExtensions.cs @@ -7,8 +7,7 @@ public static class StringExtensions /// public static bool HasNoValue(this string? value) { - return string.IsNullOrEmpty(value) - || string.IsNullOrWhiteSpace(value); + return string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value); } /// @@ -16,7 +15,6 @@ public static bool HasNoValue(this string? value) /// public static bool HasValue(this string? value) { - return !string.IsNullOrEmpty(value) - && !string.IsNullOrWhiteSpace(value); + return !string.IsNullOrEmpty(value) && !string.IsNullOrWhiteSpace(value); } } \ No newline at end of file diff --git a/src/Infrastructure.WebApi.Generators/MinimalApiMediatRGenerator.cs b/src/Infrastructure.WebApi.Generators/MinimalApiMediatRGenerator.cs index d5552a2d..ea209b26 100644 --- a/src/Infrastructure.WebApi.Generators/MinimalApiMediatRGenerator.cs +++ b/src/Infrastructure.WebApi.Generators/MinimalApiMediatRGenerator.cs @@ -28,7 +28,8 @@ public void Execute(GeneratorExecutionContext context) { var assemblyNamespace = context.Compilation.AssemblyName; var serviceClasses = GetWebApiServiceOperationsFromAssembly(context) - .GroupBy(registrations => registrations.Class.TypeName).ToList(); + .GroupBy(registrations => registrations.Class.TypeName) + .ToList(); var classUsingNamespaces = BuildUsingList(serviceClasses); var handlerClasses = new StringBuilder(); @@ -74,8 +75,11 @@ private static string BuildUsingList( var usingList = new StringBuilder(); var allNamespaces = serviceClasses.SelectMany(serviceClass => serviceClass) - .SelectMany(registration => registration.Class.UsingNamespaces).Concat(RequiredUsingNamespaces).Distinct() - .OrderByDescending(s => s).ToList(); + .SelectMany(registration => registration.Class.UsingNamespaces) + .Concat(RequiredUsingNamespaces) + .Distinct() + .OrderByDescending(s => s) + .ToList(); allNamespaces.ForEach(@using => usingList.AppendLine($"using {@using};")); @@ -104,9 +108,9 @@ private static void BuildEndpointRegistrations( { endpointRegistrations.AppendLine( $" {groupName}.{routeEndpointMethod}(\"{registration.RoutePath}\","); - if (registration.OperationType == WebApiOperation.Get || - registration.OperationType == WebApiOperation.Search || - registration.OperationType == WebApiOperation.Delete) + if (registration.OperationType == WebApiOperation.Get + || registration.OperationType == WebApiOperation.Search + || registration.OperationType == WebApiOperation.Delete) { endpointRegistrations.AppendLine( $" async (global::MediatR.IMediator mediator, [global::Microsoft.AspNetCore.Http.AsParameters] global::{registration.RequestDtoType.FullName} request) =>"); @@ -148,16 +152,16 @@ private static void BuildHandlerClasses( } handlerClasses.AppendLine( - $" public class {handlerClassName} : global::MediatR.IRequestHandler"); + $" public class {handlerClassName} : global::MediatR.IRequestHandler"); handlerClasses.AppendLine(" {"); if (constructorAndFields.HasValue()) { handlerClasses.AppendLine(constructorAndFields); } - handlerClasses.AppendLine($" public async Task" + - $" Handle(global::{registration.RequestDtoType.FullName} request, global::System.Threading.CancellationToken cancellationToken)"); + handlerClasses.AppendLine($" public async Task" + + $" Handle(global::{registration.RequestDtoType.FullName} request, global::System.Threading.CancellationToken cancellationToken)"); handlerClasses.AppendLine(" {"); var callingParameters = BuildInjectedParameters(registration.Class.Constructors.ToList()); handlerClasses.AppendLine( diff --git a/src/Infrastructure.WebApi.Generators/WebApiAssemblyVisitor.cs b/src/Infrastructure.WebApi.Generators/WebApiAssemblyVisitor.cs index 50c47eeb..7d6bc4e4 100644 --- a/src/Infrastructure.WebApi.Generators/WebApiAssemblyVisitor.cs +++ b/src/Infrastructure.WebApi.Generators/WebApiAssemblyVisitor.cs @@ -273,15 +273,18 @@ List GetConstructors() } } - var body = constructor.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax().ToFullString(); + var body = constructor.DeclaringSyntaxReferences.FirstOrDefault() + ?.GetSyntax() + .ToFullString(); ctors.Add(new Constructor { IsInjectionCtor = isInjectionCtor, CtorParameters = constructor.Parameters.Select(param => new ConstructorParameter - { - TypeName = new TypeName(param.Type.ContainingNamespace.ToDisplayString(), param.Type.Name), - VariableName = param.Name - }).ToList(), + { + TypeName = new TypeName(param.Type.ContainingNamespace.ToDisplayString(), param.Type.Name), + VariableName = param.Name + }) + .ToList(), MethodBody = body }); } @@ -291,20 +294,23 @@ List GetConstructors() List GetServiceOperationMethods() { - return symbol.GetMembers().OfType().Where(method => - { - if (IsIncorrectReturnType(method)) + return symbol.GetMembers() + .OfType() + .Where(method => { - return false; - } + if (IsIncorrectReturnType(method)) + { + return false; + } - if (HasWrongSetOfParameters(method)) - { - return false; - } + if (HasWrongSetOfParameters(method)) + { + return false; + } - return true; - }).ToList(); + return true; + }) + .ToList(); } List GetUsingNamespaces() @@ -315,15 +321,21 @@ List GetUsingNamespaces() return new List(); } - var usingSyntaxes = syntaxReference.SyntaxTree.GetRoot().DescendantNodes().OfType(); + var usingSyntaxes = syntaxReference.SyntaxTree.GetRoot() + .DescendantNodes() + .OfType(); - return usingSyntaxes.Select(us => us.Name!.ToString()).Distinct().OrderDescending().ToList(); + return usingSyntaxes.Select(us => us.Name!.ToString()) + .Distinct() + .OrderDescending() + .ToList(); } AttributeData? GetRouteAttribute(ISymbol method) { - return method.GetAttributes().FirstOrDefault(attribute => - SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, _webRouteAttributeSymbol)); + return method.GetAttributes() + .FirstOrDefault(attribute => + SymbolEqualityComparer.Default.Equals(attribute.AttributeClass, _webRouteAttributeSymbol)); } // We assume that the return type is a Task diff --git a/src/IntegrationTesting.WebApi.Common/WebApiSpec.cs b/src/IntegrationTesting.WebApi.Common/WebApiSpec.cs index 379ed1cf..f1ba9868 100644 --- a/src/IntegrationTesting.WebApi.Common/WebApiSpec.cs +++ b/src/IntegrationTesting.WebApi.Common/WebApiSpec.cs @@ -27,7 +27,8 @@ public TInterface GetRequiredService() { if (_scope is null) { - _scope = Services.GetRequiredService().CreateScope(); + _scope = Services.GetRequiredService() + .CreateScope(); } return _scope.ServiceProvider.GetRequiredService(); diff --git a/src/SaaStack.sln.DotSettings b/src/SaaStack.sln.DotSettings index 9d8206ab..dd0677b7 100644 --- a/src/SaaStack.sln.DotSettings +++ b/src/SaaStack.sln.DotSettings @@ -15,7 +15,9 @@ 1 False False + True True + CHOP_ALWAYS CHOP_ALWAYS <?xml version="1.0" encoding="utf-16"?> <Patterns xmlns="urn:schemas-jetbrains-com:member-reordering-patterns"> diff --git a/src/UnitTesting.Common/Validation/ExceptionAssertionExtensions.cs b/src/UnitTesting.Common/Validation/ExceptionAssertionExtensions.cs index ce308cc3..fc49a557 100644 --- a/src/UnitTesting.Common/Validation/ExceptionAssertionExtensions.cs +++ b/src/UnitTesting.Common/Validation/ExceptionAssertionExtensions.cs @@ -11,10 +11,16 @@ public static class ExceptionAssertionExtensions { internal static bool IsFormattedFrom(string actualExceptionMessage, string expectedMessageWithFormatters) { - var escapedPattern = expectedMessageWithFormatters.Replace("[", "\\[").Replace("]", "\\]").Replace("(", "\\(") - .Replace(")", "\\)").Replace(".", "\\.").Replace("<", "\\<").Replace(">", "\\>"); + var escapedPattern = expectedMessageWithFormatters.Replace("[", "\\[") + .Replace("]", "\\]") + .Replace("(", "\\(") + .Replace(")", "\\)") + .Replace(".", "\\.") + .Replace("<", "\\<") + .Replace(">", "\\>"); - var pattern = escapedPattern.ReplaceWith(@"\{\d+\}", ".*").Replace(" ", @"\s"); + var pattern = escapedPattern.ReplaceWith(@"\{\d+\}", ".*") + .Replace(" ", @"\s"); return actualExceptionMessage.IsMatchWith(pattern); } @@ -27,9 +33,11 @@ public static ExceptionAssertions WithMessageLike( if (!string.IsNullOrEmpty(messageWithFormatters)) { var exception = @throw.Subject.Single(); - var expectedFormat = messageWithFormatters.Replace("{", "{{").Replace("}", "}}"); + var expectedFormat = messageWithFormatters.Replace("{", "{{") + .Replace("}", "}}"); Execute.Assertion.BecauseOf(because, becauseArgs) - .ForCondition(IsFormattedFrom(exception.Message, messageWithFormatters)).UsingLineBreaks.FailWith( + .ForCondition(IsFormattedFrom(exception.Message, messageWithFormatters)) + .UsingLineBreaks.FailWith( $"Expected exception message to match the equivalent of\n\"{expectedFormat}\", but\n\"{exception.Message}\" does not."); } @@ -44,9 +52,11 @@ public static async Task> WithMessageLike