Ejemplo n.º 1
0
 private void SetValidationResponse(
     ActionExecutingContext actionContext,
     ValidationErrorDetails validationErrorDetails)
 {
     actionContext.Result = new ResourceValidationResult(
         validationErrorDetails);
 }
Ejemplo n.º 2
0
        private async Task SetValidationResponse(
            HttpActionContext actionContext,
            CancellationToken cancellationToken,
            ValidationErrorDetails validationErrorDetails)
        {
            var result   = new ResourceValidationResult(actionContext.Request, validationErrorDetails);
            var response = await result.ExecuteAsync(cancellationToken);

            actionContext.Response = response;
        }
        public async Task ValidationExceptionShouldReturn422(
            SampleServerFactory serverFactory,
            Mock <IValuesRepository> valuesRepository,
            ValidationErrorDetails errorDetails,
            int entityId)
        {
            valuesRepository.Setup(r => r.GetValue(It.IsAny <int>()))
            .Throws(new EntityValidationException(errorDetails));

            using (var server = serverFactory.With <IValuesRepository>(valuesRepository.Object).Create())
            {
                var response = await server.HttpClient.GetAsync($"/api/values/{entityId}");

                Assert.Equal((HttpStatusCode)422, response.StatusCode);
            }
        }
        private async Task <List <ValidationErrorDto> > ReadAndDeserialiseValidationErrorsAsync(IReportServiceContext reportServiceContext, CancellationToken cancellationToken)
        {
            List <ValidationErrorDto> result = new List <ValidationErrorDto>();

            try
            {
                string validationErrorsStr = await _streamableKeyValuePersistenceService.GetAsync(reportServiceContext.ValidationErrorsKey, cancellationToken);

                try
                {
                    List <ValidationError> validationErrors = _jsonSerializationService.Deserialize <List <ValidationError> >(validationErrorsStr);

                    // Extract the rules names and fetch the details for them.
                    string[] rulesNames = validationErrors.Select(x => x.RuleName).Distinct().ToArray();
                    List <ValidationErrorDetails> validationErrorDetails = rulesNames.Select(x => new ValidationErrorDetails(x)).ToList();
                    await _validationErrorsService.PopulateValidationErrors(rulesNames, validationErrorDetails, cancellationToken);

                    foreach (ValidationError validationError in validationErrors)
                    {
                        ValidationErrorDetails validationErrorDetail = validationErrorDetails.SingleOrDefault(x => string.Equals(x.RuleName, validationError.RuleName, StringComparison.OrdinalIgnoreCase));

                        result.Add(new ValidationErrorDto
                        {
                            AimSequenceNumber      = validationError.AimSequenceNumber,
                            LearnerReferenceNumber = validationError.LearnerReferenceNumber,
                            RuleName     = validationError.RuleName,
                            Severity     = validationError.Severity,
                            ErrorMessage = validationErrorDetail?.Message,
                            FieldValues  = validationError.ValidationErrorParameters == null
                                ? string.Empty
                                : GetValidationErrorParameters(validationError.ValidationErrorParameters.ToList()),
                        });
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError("Failed to merge validation error messages", ex);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Can't process validation errors", ex);
            }

            return(result);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Converts validation error details to the dto.
        /// </summary>
        /// <param name="validationErrorDetails">The validation error details.</param>
        /// <param name="code">The code.</param>
        /// <returns>The DTO.</returns>
        public static ResourceValidationApiModel ToDto(this ValidationErrorDetails validationErrorDetails, string code)
        {
            if (validationErrorDetails == null)
            {
                throw new ArgumentNullException(nameof(validationErrorDetails));
            }

            return(new ResourceValidationApiModel
            {
                Message = validationErrorDetails.Message,
                Code = code,
                Errors = validationErrorDetails.Errors.Select(e => new ResourceValidationErrorApiModel
                {
                    Message = e.Message,
                    Resource = e.Resource,
                    Field = e.Field,
                    Code = e.Code.ToString().Kebaberize(),
                }),
            });
        }
        public async Task TestValidationReportGeneration()
        {
            string csv  = string.Empty;
            string json = string.Empty;

            byte[]   xlsx        = null;
            DateTime dateTime    = DateTime.UtcNow;
            string   filename    = $"10000020_1_Rule Violation Report {dateTime:yyyyMMdd-HHmmss}";
            string   ilrFilename = @"Reports\Validation\ILR-10000020-1819-20181005-120953-03.xml";

            Mock <ILogger> logger = new Mock <ILogger>();
            Mock <IStreamableKeyValuePersistenceService> storage        = new Mock <IStreamableKeyValuePersistenceService>();
            IXmlSerializationService        xmlSerializationService     = new XmlSerializationService();
            IJsonSerializationService       jsonSerializationService    = new JsonSerializationService();
            Mock <IDateTimeProvider>        dateTimeProviderMock        = new Mock <IDateTimeProvider>();
            IValueProvider                  valueProvider               = new ValueProvider();
            IIntUtilitiesService            intUtilitiesService         = new IntUtilitiesService();
            Mock <IValidationErrorsService> validationErrorsServiceMock = new Mock <IValidationErrorsService>();

            storage.Setup(x => x.ContainsAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())).ReturnsAsync(true);
            storage.Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())).ReturnsAsync(File.ReadAllText(ilrFilename));
            storage.Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <Stream>(), It.IsAny <CancellationToken>()))
            .Callback <string, Stream, CancellationToken>((st, sr, ct) => File.OpenRead(ilrFilename).CopyTo(sr)).Returns(Task.CompletedTask);
            storage.Setup(x => x.SaveAsync($"{filename}.csv", It.IsAny <string>(), It.IsAny <CancellationToken>())).Callback <string, string, CancellationToken>((key, value, ct) => csv   = value).Returns(Task.CompletedTask);
            storage.Setup(x => x.SaveAsync($"{filename}.json", It.IsAny <string>(), It.IsAny <CancellationToken>())).Callback <string, string, CancellationToken>((key, value, ct) => json = value).Returns(Task.CompletedTask);
            storage.Setup(x => x.SaveAsync($"{filename}.xlsx", It.IsAny <Stream>(), It.IsAny <CancellationToken>())).Callback <string, Stream, CancellationToken>(
                (key, value, ct) =>
            {
                value.Seek(0, SeekOrigin.Begin);
                using (MemoryStream ms = new MemoryStream())
                {
                    value.CopyTo(ms);
                    xlsx = ms.ToArray();
                }
            })
            .Returns(Task.CompletedTask);
            storage.Setup(x => x.GetAsync("ValidationErrors", It.IsAny <CancellationToken>())).ReturnsAsync(File.ReadAllText(@"Reports\Validation\ValidationErrors.json"));
            dateTimeProviderMock.Setup(x => x.GetNowUtc()).Returns(dateTime);
            dateTimeProviderMock.Setup(x => x.ConvertUtcToUk(It.IsAny <DateTime>())).Returns(dateTime);
            validationErrorsServiceMock.Setup(x => x.PopulateValidationErrors(It.IsAny <string[]>(), It.IsAny <List <ValidationErrorDetails> >(), It.IsAny <CancellationToken>())).Callback <string[], List <ValidationErrorDetails>, CancellationToken>(
                (s, v, c) =>
            {
                List <ValidationErrorDetails> validationErrorDetails = jsonSerializationService.Deserialize <List <ValidationErrorDetails> >(File.ReadAllText(@"Reports\Validation\ValidationErrorsLookup.json"));
                foreach (ValidationErrorDetails veds in v)
                {
                    ValidationErrorDetails rule = validationErrorDetails.SingleOrDefault(x => string.Equals(x.RuleName, veds.RuleName, StringComparison.OrdinalIgnoreCase));
                    if (rule != null)
                    {
                        veds.Message  = rule.Message;
                        veds.Severity = rule.Severity;
                    }
                }
            }).Returns(Task.CompletedTask);

            IIlrProviderService ilrProviderService = new IlrProviderService(logger.Object, storage.Object, xmlSerializationService, dateTimeProviderMock.Object, intUtilitiesService, null, null);

            ITopicAndTaskSectionOptions topicsAndTasks             = TestConfigurationHelper.GetTopicsAndTasks();
            IValidationStageOutputCache validationStageOutputCache = new ValidationStageOutputCache();

            IReport validationErrorsReport = new ValidationErrorsReport(
                logger.Object,
                storage.Object,
                jsonSerializationService,
                ilrProviderService,
                dateTimeProviderMock.Object,
                valueProvider,
                topicsAndTasks,
                validationErrorsServiceMock.Object,
                validationStageOutputCache);

            Mock <IReportServiceContext> reportServiceContextMock = new Mock <IReportServiceContext>();

            reportServiceContextMock.SetupGet(x => x.JobId).Returns(1);
            reportServiceContextMock.SetupGet(x => x.SubmissionDateTimeUtc).Returns(DateTime.UtcNow);
            reportServiceContextMock.SetupGet(x => x.Ukprn).Returns(10000020);
            reportServiceContextMock.SetupGet(x => x.Filename).Returns(@"Reports\Validation\" + Path.GetFileNameWithoutExtension(ilrFilename));
            reportServiceContextMock.SetupGet(x => x.ValidationErrorsKey).Returns("ValidationErrors");
            reportServiceContextMock.SetupGet(x => x.ValidationErrorsLookupsKey).Returns("ValidationErrorsLookup");
            reportServiceContextMock.SetupGet(x => x.ValidLearnRefNumbersCount).Returns(2);
            reportServiceContextMock.SetupGet(x => x.InvalidLearnRefNumbersCount).Returns(3);
            reportServiceContextMock.SetupGet(x => x.CollectionName).Returns("ILR1819");

            await validationErrorsReport.GenerateReport(reportServiceContextMock.Object, null, false, CancellationToken.None);

            json.Should().NotBeNullOrEmpty();
            csv.Should().NotBeNullOrEmpty();
            xlsx.Should().NotBeNullOrEmpty();

#if DEBUG
            File.WriteAllBytes($"{filename}.xlsx", xlsx);
#endif

            ValidationErrorMapper helper = new ValidationErrorMapper();
            TestCsvHelper.CheckCsv(csv, new CsvEntry(helper, 1));
            TestXlsxHelper.CheckXlsx(xlsx, new XlsxEntry(helper, 5));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceValidationResult"/> class.
 /// </summary>
 /// <param name="errorDetails">The error details.</param>
 public ResourceValidationResult(ValidationErrorDetails errorDetails)
     : base(new EntityValidationApiEvent(errorDetails))
 {
 }
Ejemplo n.º 8
0
        /// <inheritdoc />
        protected override void ConfigureMappings(HttpResponseExceptionConfiguration configuration)
        {
            configuration.AddMapping(
                HttpStatusCode.Unauthorized,
                (r, c) => new UnauthenticatedException(
                    c.Formatter.Code(r.Property("code")),
                    c.Formatter.Message(r.Property("message"))));

            configuration.AddMapping(
                HttpStatusCode.Forbidden,
                "AR403",
                (r, c) => new EntityPermissionException(
                    c.Formatter.Code(r.Property("code")),
                    userId: c.Formatter.EntityProperty(r.Property("userId")),
                    entityType: c.Formatter.EntityType(r.Property("resource")),
                    entityId: c.Formatter.EntityProperty(r.Property("resourceId"))));

            configuration.AddMapping(
                HttpStatusCode.Forbidden,
                "AR403C",
                (r, c) => new EntityCreatePermissionException(
                    c.Formatter.Code(r.Property("code")),
                    c.Formatter.EntityProperty(r.Property("userId")),
                    c.Formatter.EntityType(r.Property("resource")),
                    c.Formatter.EntityType(r.Property("resourceId"))));

            configuration.AddMapping(
                (HttpStatusCode)422,
                (r, c) =>
            {
                var errorsResponse = r.Property <List <ResourceValidationErrorApiModel> >("errors");
                var errors         = errorsResponse?.Select(e => new ValidationError(
                                                                resource: c.Formatter.EntityType(e.Resource),
                                                                field: c.Formatter.EntityProperty(e.Field),
                                                                code: ToValidationErrorCode(e.Code),
                                                                errorMessage: c.Formatter.Message(e.Message))) ?? Enumerable.Empty <ValidationError>();

                var errorDetails = new ValidationErrorDetails(c.Formatter.Message(r.Property("message")), errors);
                return(new EntityValidationException(
                           code: c.Formatter.Code(r.Property("code")),
                           errorDetails: errorDetails));
            });

            configuration.AddMapping(
                HttpStatusCode.NotFound,
                "AR404",
                (r, c) => new EntityNotFoundException(
                    c.Formatter.Code(r.Property("code")),
                    entityType: c.Formatter.EntityType(r.Property("resource")),
                    entityId: c.Formatter.EntityProperty(r.Property("resourceId"))));

            configuration.AddMapping(
                HttpStatusCode.NotFound,
                "AR404Q",
                (r, c) => new EntityNotFoundQueryException(
                    c.Formatter.Code(r.Property("code")),
                    c.Formatter.EntityType(r.Property("resource")),
                    r.Property <IEnumerable <QueryParameterDto> >("queryParameters").Select(qp => new QueryParameter(qp.Key, qp.Value))));

            configuration.AddMapping(
                HttpStatusCode.InternalServerError,
                (r, c) => new ServiceErrorException(
                    c.Formatter.Code(r.Property("code")),
                    new Exception(c.Formatter.Message(r.Property("message")))));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceValidationResult"/> class.
 /// </summary>
 /// <param name="request">The request.</param>
 /// <param name="errorDetails">The error details.</param>
 public ResourceValidationResult(HttpRequestMessage request, ValidationErrorDetails errorDetails)
     : base(request, new EntityValidationApiEvent(errorDetails))
 {
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EntityValidationApiEvent"/> class.
 /// </summary>
 /// <param name="errorDetails">The error details.</param>
 public EntityValidationApiEvent(ValidationErrorDetails errorDetails)
     : this("AR422", errorDetails)
 {
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EntityValidationApiEvent"/> class.
 /// </summary>
 /// <param name="code">The code.</param>
 /// <param name="errorDetails">The error details.</param>
 public EntityValidationApiEvent(string code, ValidationErrorDetails errorDetails)
 {
     this.Code         = code;
     this.ErrorDetails = errorDetails ?? throw new ArgumentNullException(nameof(errorDetails));
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EntityValidationException"/> class.
 /// </summary>
 /// <param name="errorDetails">The error details.</param>
 public EntityValidationException(ValidationErrorDetails errorDetails)
     : base(errorDetails.Message, new EntityValidationApiEvent(errorDetails))
 {
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EntityValidationException"/> class.
 /// </summary>
 /// <param name="code">The code.</param>
 /// <param name="errorDetails">The error details.</param>
 public EntityValidationException(string code, ValidationErrorDetails errorDetails)
     : base(errorDetails.Message, new EntityValidationApiEvent(code, errorDetails))
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourceValidationHttpResponse"/> class.
 /// </summary>
 /// <param name="code">The code.</param>
 /// <param name="validationErrorDetails">The validation error details.</param>
 public ResourceValidationHttpResponse(string code, ValidationErrorDetails validationErrorDetails)
     : base(validationErrorDetails.ToDto(code), (HttpStatusCode)422)
 {
 }