Beispiel #1
0
 public static void ToModelErrors_ReturnsExpectedResult(
     string field,
     string id,
     AggregateValidationResult aggregateResult)
 {
     var expectedKey    = $"[0].{field}";
     var expectedErrors = new (string, string)[]
        public static async Task CreateAsync_CatalogueItemSavedToDb(
            [Frozen] ApplicationDbContext context,
            [Frozen] Mock <ICreateOrderItemValidator> orderItemValidator,
            [Frozen] Mock <IServiceRecipientService> serviceRecipientService,
            Order order,
            CatalogueItemId catalogueItemId,
            CreateOrderItemModel model,
            CreateOrderItemService service)
        {
            context.Order.Add(order);
            await context.SaveChangesAsync();

            var aggregateValidationResult = new AggregateValidationResult();

            aggregateValidationResult.AddValidationResult(new ValidationResult(), 0);

            var catalogueItemType = Enum.Parse <CatalogueItemType>(model.CatalogueItemType, true);

            var serviceRecipients = model.ServiceRecipients.Select(r => new ServiceRecipient(r.OdsCode, r.Name));

            orderItemValidator.Setup(o => o.Validate(order, model, catalogueItemType)).Returns(aggregateValidationResult);
            serviceRecipientService.Setup(r => r.AddOrUpdateServiceRecipients(It.IsAny <IEnumerable <ServiceRecipient> >()))
            .ReturnsAsync(serviceRecipients.ToDictionary(r => r.OdsCode));

            await service.CreateAsync(order, catalogueItemId, model);

            var expectedOrderItem = context.Set <OrderItem>().First(o => o.CatalogueItem.Id.Equals(catalogueItemId));

            expectedOrderItem.CatalogueItem.Name.Should().Be(model.CatalogueItemName);
        }
        public static async Task CreateAsync_RemovesDefaultDeliveryDate(
            [Frozen] ApplicationDbContext context,
            [Frozen] Mock <ICreateOrderItemValidator> orderItemValidator,
            [Frozen] Mock <IServiceRecipientService> serviceRecipientService,
            Order order,
            CatalogueItemId catalogueItemId,
            CreateOrderItemModel model,
            CreateOrderItemService service)
        {
            order.SetDefaultDeliveryDate(catalogueItemId, DateTime.Now.AddDays(10));
            context.Order.Add(order);
            await context.SaveChangesAsync();

            order.DefaultDeliveryDates.Should().NotBeEmpty();

            var aggregateValidationResult = new AggregateValidationResult();

            aggregateValidationResult.AddValidationResult(new ValidationResult(), 0);

            var catalogueItemType = Enum.Parse <CatalogueItemType>(model.CatalogueItemType, true);

            var serviceRecipients = model.ServiceRecipients.Select(r => new ServiceRecipient(r.OdsCode, r.Name));

            orderItemValidator.Setup(o => o.Validate(order, model, catalogueItemType)).Returns(aggregateValidationResult);
            serviceRecipientService.Setup(r => r.AddOrUpdateServiceRecipients(It.IsAny <IEnumerable <ServiceRecipient> >()))
            .ReturnsAsync(serviceRecipients.ToDictionary(r => r.OdsCode));

            await service.CreateAsync(order, catalogueItemId, model);

            var defaultDeliveryDateResult = context.Set <DefaultDeliveryDate>().FirstOrDefault(d => d.OrderId.Equals(order.Id));

            defaultDeliveryDateResult.Should().BeNull();
        }
        public async Task ValidateAsync_WhenRequirePackageSignatureIsTrue_RequiresPackageSignatureFile(
            bool includePackageSignatureFile)
        {
            var storage        = new MemoryStorage(_baseUri);
            var now            = GetDateTime();
            var storageContent = CreateStorageContent(now, includePackageSignatureFile);

            storage.Content.TryAdd(_packageDetailsUri, storageContent);

            using (var clientHandler = new MockServerHttpClientHandler())
                using (CollectorHttpClient client = await CreateCollectorHttpClientStubAsync(clientHandler, storage))
                {
                    ValidationContext         context   = CreateContext(client, now);
                    CatalogAggregateValidator validator = CreateValidator(context, requirePackageSignature: true);

                    AggregateValidationResult result = await validator.ValidateAsync(context);

                    Assert.Single(result.ValidationResults);

                    var expectedResult = includePackageSignatureFile ? TestResult.Pass : TestResult.Fail;
                    var actualResult   = result.ValidationResults.Single();

                    Assert.Equal(expectedResult, actualResult.Result);

                    if (includePackageSignatureFile)
                    {
                        Assert.Null(actualResult.Exception);
                    }
                    else
                    {
                        Assert.IsType <MissingPackageSignatureFileException>(actualResult.Exception);
                    }
                }
        }
Beispiel #5
0
        public static async Task CreateOrderItemsAsync_ValidationFailure_ReturnsExpectedResponse(
            ErrorDetails errorDetails,
            AggregateValidationResult aggregateValidationResult,
            [Frozen] Mock <ICreateOrderItemService> createOrderItemService,
            [Frozen] Mock <IOrderItemService> orderItemService,
            [Frozen] CallOffId callOffId,
            CatalogueItemId catalogueItemId,
            Order order,
            CreateOrderItemModel model,
            OrderItemsController controller)
        {
            controller.ProblemDetailsFactory = new TestProblemDetailsFactory();
            aggregateValidationResult.AddValidationResult(new ValidationResult(errorDetails), 0);

            Expression <Func <ICreateOrderItemService, Task <AggregateValidationResult> > > createAsync = s => s.CreateAsync(
                It.Is <Order>(o => o.Equals(order)),
                It.Is <CatalogueItemId>(i => i == catalogueItemId),
                It.Is <CreateOrderItemModel>(m => m == model));

            orderItemService.Setup(o => o.GetOrder(callOffId)).ReturnsAsync(order);
            createOrderItemService.Setup(createAsync).ReturnsAsync(aggregateValidationResult);

            var response = await controller.CreateOrderItemAsync(callOffId, catalogueItemId, model);

            response.Should().BeOfType <BadRequestObjectResult>();
            response.As <BadRequestObjectResult>().Value.Should().BeOfType <ValidationProblemDetails>();
        }
Beispiel #6
0
        public static async Task CreateOrderItemAsync_ValidationFailure_AddsModelErrors(
            [Frozen] IReadOnlyList <ErrorDetails> errorDetails,
            AggregateValidationResult aggregateValidationResult,
            [Frozen] Mock <ICreateOrderItemService> createOrderItemService,
            [Frozen] Mock <IOrderItemService> orderItemService,
            [Frozen] CallOffId callOffId,
            CatalogueItemId catalogueItemId,
            Order order,
            CreateOrderItemModel model,
            OrderItemsController controller)
        {
            controller.ProblemDetailsFactory = new TestProblemDetailsFactory();
            aggregateValidationResult.AddValidationResult(new ValidationResult(errorDetails), 0);

            Expression <Func <ICreateOrderItemService, Task <AggregateValidationResult> > > createAsync = s => s.CreateAsync(
                It.Is <Order>(o => o.Equals(order)),
                It.Is <CatalogueItemId>(i => i == catalogueItemId),
                It.Is <CreateOrderItemModel>(m => m == model));

            orderItemService.Setup(o => o.GetOrder(callOffId)).ReturnsAsync(order);
            createOrderItemService.Setup(createAsync).ReturnsAsync(aggregateValidationResult);

            await controller.CreateOrderItemAsync(callOffId, catalogueItemId, model);

            var modelState = controller.ModelState;

            modelState.ErrorCount.Should().Be(errorDetails.Count);
            modelState.Keys.Should().BeEquivalentTo(errorDetails.Select(e => e.ParentName + "[0]." + e.Field));

            var modelStateErrors = modelState.Values.Select(v => v.Errors[0].ErrorMessage);

            modelStateErrors.Should().BeEquivalentTo(errorDetails.Select(e => e.Id));
        }
Beispiel #7
0
        public static void Success_SuccessfulResultsOnly_IsTrue(
            ValidationResult result,
            AggregateValidationResult aggregateResult)
        {
            aggregateResult.AddValidationResult(result, 0);

            aggregateResult.Success.Should().BeTrue();
        }
        public void Constructor_maps_arguments()
        {
            var results         = new List <ValidationResult>();
            var aggregateResult = new AggregateValidationResult("New aggregate", results);

            aggregateResult.AggregateName.Should().Be("New aggregate");
            aggregateResult.MemberNames.Should().HaveCount(1);
            aggregateResult.Results.Equals(results);
        }
Beispiel #9
0
        public static void Success_FailedResults_IsFalse(
            ErrorDetails error,
            AggregateValidationResult aggregateResult)
        {
            var result = new ValidationResult(error);

            aggregateResult.AddValidationResult(result, 0);

            aggregateResult.Success.Should().BeFalse();
        }
Beispiel #10
0
        public static void AssertAggregateValidationResult(AggregateValidationResult expected, AggregateValidationResult actual)
        {
            if (expected == null)
            {
                Assert.Null(actual);

                return;
            }

            AssertFieldEqual(expected, actual, i => i.AggregateValidator.Name);
            AssertFieldEqual(expected, actual, i => i.ValidationResults, AssertValidationResult);
        }
Beispiel #11
0
        public static void AddValidationResult_CombinesExistingResults(
            ErrorDetails error1,
            ErrorDetails error2,
            AggregateValidationResult aggregateResult)
        {
            var result1 = new ValidationResult(error1);
            var result2 = new ValidationResult(error2);

            aggregateResult.AddValidationResult(result1, 0);
            aggregateResult.AddValidationResult(result2, 0);

            aggregateResult.FailedValidations.Should().HaveCount(1);
        }
        public static async Task CreateAsync_ValidAggregateValidation_SuccessIsTrue(
            [Frozen] Mock <ICreateOrderItemValidator> orderItemValidator,
            Order order,
            CatalogueItemId catalogueItemId,
            CreateOrderItemModel model,
            CreateOrderItemService service)
        {
            var aggregateValidationResult = new AggregateValidationResult();

            aggregateValidationResult.AddValidationResult(new ValidationResult(), 0);

            var catalogueItemType = Enum.Parse <CatalogueItemType>(model.CatalogueItemType, true);

            orderItemValidator.Setup(o => o.Validate(order, model, catalogueItemType)).Returns(aggregateValidationResult);

            var result = await service.CreateAsync(order, catalogueItemId, model);

            result.Success.Should().BeTrue();
        }
Beispiel #13
0
        public AggregateValidationResult Validate(Order order, CreateOrderItemModel model, CatalogueItemType itemType)
        {
            if (order.CommencementDate is null)
            {
                throw new ArgumentNullException(nameof(order), $"{nameof(order)}.{nameof(Order.CommencementDate)} should not be null.");
            }

            var aggregateValidationResult = new AggregateValidationResult();
            var itemIndex = -1;

            foreach (var recipient in model.ServiceRecipients)
            {
                itemIndex++;
                aggregateValidationResult.AddValidationResult(
                    new ValidationResult(ValidateDeliveryDate(recipient.DeliveryDate, order.CommencementDate.Value, itemType)),
                    itemIndex);
            }

            return(aggregateValidationResult);
        }
        public async Task ValidateAsync_WhenRequirePackageSignatureIsFalse_DoesNotRequirePackageSignatureFile(
            bool includePackageSignatureFile)
        {
            var storage        = new MemoryStorage(_baseUri);
            var now            = GetDateTime();
            var storageContent = CreateStorageContent(now, includePackageSignatureFile);

            storage.Content.TryAdd(_packageDetailsUri, storageContent);

            using (var clientHandler = new MockServerHttpClientHandler())
                using (CollectorHttpClient client = await CreateCollectorHttpClientStubAsync(clientHandler, storage))
                {
                    ValidationContext         context   = CreateContext(client, now);
                    CatalogAggregateValidator validator = CreateValidator(context, requirePackageSignature: false);

                    AggregateValidationResult result = await validator.ValidateAsync(context);

                    Assert.Empty(result.ValidationResults);
                }
        }
            public void Invalid()
            {
                var validationResults = new ValidationResult[]
                {
                    new ValidationResult(null, TestResult.Fail)
                };

                var aggregateValidationResults = new AggregateValidationResult(
                    null,
                    validationResults);

                var packageValidationResult = new PackageValidationResult(
                    new PackageIdentity("testPackage", new NuGetVersion(4, 5, 6)),
                    null,
                    null,
                    new AggregateValidationResult[] { aggregateValidationResults });

                var status = new PackageMonitoringStatus(packageValidationResult);

                Assert.Equal(PackageState.Invalid, status.State);
            }
Beispiel #16
0
 public static void AddValidationResult_NullResult_ThrowsException(AggregateValidationResult aggregateResult)
 {
     Assert.Throws <ArgumentNullException>(() => aggregateResult.AddValidationResult(null, 0));
 }