/// <summary>
 /// Конструктор, копирующий значения из переданного объекта.
 /// </summary>
 /// <param name="source">Объект, значения которого необходимо скопировать.</param>
 public GetProgramsResponseHelper(GetProgramsResponse source)
 {
     source = source ?? throw new ArgumentNullException(nameof(source));
     CopyFrom(source);
     ProgramsSingular = source.Programs;
     ProgramsPlural   = source.Programs;
 }
#pragma warning restore CA1819 // Properties should not return arrays
#pragma warning restore SA1011 // Closing square brackets should be spaced correctly

        /// <summary>
        /// Копирует в предоставленный объект поля из данного объекта.
        /// </summary>
        /// <returns>Заполненный объект.</returns>
        public GetProgramsResponse CreateResponse()
        {
            var retVal = new GetProgramsResponse();

            CopyTo(retVal);
            retVal.Programs = ProgramsPlural ?? ProgramsSingular ?? new List <GetProgramsResponse.Program>();
            return(retVal);
        }
        public async Task ItWorks(bool useEmptyRawRequestProcessor)
        {
            var sampleProgramName = "Программа 2+2 - скидка 22%";

            var jsonText  = "{\"pos_id\": \"123\"}";
            var jsonBytes = Encoding.UTF8.GetBytes(jsonText);

            using var body = new MemoryStream();
            body.Write(jsonBytes, 0, jsonBytes.Length);
            body.Position = 0;

            context.Request.Method      = "POST";
            context.Request.Path        = "/get_programs";
            context.Request.ContentType = "application/json";
            context.Request.Body        = body;

            context.Response.Body = new MemoryStream();

            var sampleResponse = new GetProgramsResponse
            {
                Status    = Globals.StatusSuccess,
                ErrorCode = 0,
                Message   = nameof(ItWorks),
                Programs  = { new GetProgramsResponse.Program {
                                  Code = "1", Name = sampleProgramName
                              } },
            };

            likeServiceMock
            .Setup(x => x.GetProgramsAsync(It.Is <GetProgramsRequest>(grp => grp.PosId == "123"), It.IsNotNull <SampleUserInfo>()))
            .ReturnsAsync(sampleResponse)
            .Verifiable();

            if (useEmptyRawRequestProcessor)
            {
                options.RawRequestProcessor = (context, user) => null;
            }

            await middleware.InvokeAsync(context).ConfigureAwait(false);

            Assert.Equal(200, context.Response.StatusCode);
            likeServiceMock.Verify();

            context.Response.Body.Position = 0;

            using var sr = new StreamReader(context.Response.Body);
            var resp = await sr.ReadToEndAsync().ConfigureAwait(false);

            Assert.Contains(options.JsonSerializerOptions.Encoder.Encode(sampleProgramName), resp, StringComparison.Ordinal);
        }
Example #4
0
        private static void Validate(GetProgramsResponse value, string suffix)
        {
            value = value ?? throw new ArgumentNullException(nameof(value));

            Assert.Equal("error", value.Status);
            Assert.Equal(11, value.ErrorCode);
            Assert.Equal("Hello, World!", value.Message);

            Assert.NotNull(value.Programs);
            Assert.Equal(2, value.Programs.Count);
            Assert.Equal("code1" + suffix, value.Programs[0].Code);
            Assert.Equal("name1" + suffix, value.Programs[0].Name);
            Assert.Equal("code2" + suffix, value.Programs[1].Code);
            Assert.Equal("name2" + suffix, value.Programs[1].Name);
        }
        public GetProgramsResponse GetPrograms()
        {
            GetProgramsResponse response = new GetProgramsResponse();

            try
            {
                response.Programs = _programsRepository.GetPrograms().ToList();
            }
            catch (Exception ex)
            {
                response.IsSuccessful = false;
                response.Errors.Add("An error has occurred while getting all programs!");
                _logger.LogException(ex);
            }
            return(response);
        }
Example #6
0
        /// <summary>
        /// Выполняет валидацию объекта с учётом вложенных коллекций (Orders, Products, ...), используя <see cref="ProtocolSettings">параметры протокола</see>, заданные в конструкторе.
        /// </summary>
        /// <param name="instance">Экземпляр объекта для проверки.</param>
        /// <param name="results">Список, который необходимо заполнить ошибками (если они будут найдены).</param>
        /// <returns>Результат валидации: <b>true</b> в случае успешной валидации или <b>false</b> если были обнаружены ошибки.</returns>
        public bool TryValidateObject(object instance, out List <ValidationResult> results)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }

            var psp = new ProtocolSettingsServiceProvider(protocolSettings);

            var vc = new ValidationContext(instance, psp, null);

            results = new List <ValidationResult>();

            var isValid = Validator.TryValidateObject(instance, vc, results, true);

            IEnumerable <object>?children = instance switch
            {
                GetDiscountRequest gdr => gdr.Orders,
                GetDiscountResponse gdr => gdr.Orders,
                ConfirmPurchaseRequest cpr => cpr.Skus,
                GetProgramsResponse gpr => gpr.Programs,
                GetProductsResponse gpr => gpr.Products,
                UpdatePharmaciesRequest upr => upr.Pharmacies,
                                _ => null,
            };

            if (children != null)
            {
                foreach (var child in children)
                {
                    if (child != null)
                    {
                        var childvc = new ValidationContext(child, psp, null);
                        isValid &= Validator.TryValidateObject(child, childvc, results, true);
                    }
                }
            }

            return(isValid);
        }
        // <inheritdocs />
        public Task <GetProgramsResponse> GetProgramsAsync(GetProgramsRequest request, string user)
        {
            var resp = new GetProgramsResponse
            {
                Status    = Globals.StatusSuccess,
                ErrorCode = 0,
                Message   = "Данные сформированы",
                Programs  = new List <GetProgramsResponse.Program>
                {
                    new GetProgramsResponse.Program
                    {
                        Code = "SAMPLE1",
                        Name = "Программа 1",
                    },
                    new GetProgramsResponse.Program
                    {
                        Code = "SAMPLE2",
                        Name = "Программа 2",
                    },
                },
            };

            return(Task.FromResult(resp));
        }